clearInterval不会停止setInterval

时间:2015-12-09 17:12:18

标签: javascript canvas

我在javascript中使用这款游戏进行砖块游戏。问题是我的clearInterval函数即使全局声明也不想停止。我在这里添加了我的绘图函数,每次调用setInterval时都会渲染画布。

initbricks();
draw();
init_mouse();
var i = setInterval(draw,100);  

function play(){    
    document.getElementById("play").disabled = true;
}     

function reset(){
    clear();
    clearInterval(i);
}

//Initialize game
function init() {
    document.getElementById("play").addEventListener("click", play);
    document.getElementById("reset").addEventListener("click", reset);
}

//Load canvas after window has loaded
if (document.getElementById) window.onload=init;

function draw() {
    clear();
    circle(ballX,ballY,radius);  
    rect(paddlex, height-paddleh, paddlew, paddleh);

    //draw bricks
    for (i=0; i < NROWS; i++) {
        ctx.fillStyle = rowcolors[i];  
        for (j=0; j < NCOLS; j++) {
            if (bricks[i][j] == 1) {
                rect((j * (BRICKWIDTH + PADDING)) + PADDING, 
                     (i * (BRICKHEIGHT + PADDING)) + PADDING,
                     BRICKWIDTH, BRICKHEIGHT);
            }
        }
    }

    // hit brick?
    rowheight = BRICKHEIGHT + PADDING;
    colwidth = BRICKWIDTH + PADDING;
    row = Math.floor(ballY/rowheight);
    col = Math.floor(ballX/colwidth);
    // if so, reverse the ball and mark the brick as broken
    if (ballY<NROWS*rowheight && row>=0 && col>=0 && bricks[row][col]==1) {
        dy = -dy;
        bricks[row][col] = 0;
    }

    // if game not over, move paddle
    if (ballY+dy<height)
        if (rightDown && paddlex+paddlew<width)
            paddlex += 5;
        else if (leftDown && paddlex>0)
            paddlex -= 5;

    // Right/Left stop condition
    if (ballX+dx>width-5 || ballX+dx<5)
        dx= -dx;

    // Up stop condition
    if (ballY+dy<5)
        dy= -dy;

    // Down stop condition
    else 
        //i f ball is on the paddle
        if (ballY+dy>height-20 && ballX>paddlex && ballX<paddlex+paddlew) 
            dy= -dy;

    // if ball is not on the paddle
    else if (ballY+dy>height+20){
        // game over, so stop the animation
        clearInterval(i);
    }                                                 
    ballX += dx;
    ballY += dy;
}

2 个答案:

答案 0 :(得分:2)

您有多个名为i的变量,而draw函数中的一个变量未被赋予var声明说明符,因此它已被赋予window.requestAnimationFrame。覆盖你的计时器变量。

无论如何(双关语无意)你应该调查record va textv numv datev 1 1 a NULL NULL 1 2 NULL 1 NULL 1 3 NULL NULL 1 jan 2015 2 1 b NULL NULL 2 2 NULL 45 NULL 3 1 c NULL NULL 3 3 NULL NULL 5 feb 2015 来处理你的屏幕刷新,而根本不使用计时器。它会让你的游戏动画更加顺畅。

答案 1 :(得分:2)

for (i=0; i < NROWS; i++) {

似乎变量i已被for循环替换。

重命名区间变量名称