[英]clearInterval won't stop setInterval
I have this piece of game for a bricks game in javascript. 我有一段用javascript制作的游戏。 The thing is that my clearInterval function doesn't want to stop even if it's globally declared. 事实是,即使我的clearInterval函数是全局声明的,也不想停止。 I added here my draw function which renders the canvas each time when that setInterval is called. 我在这里添加了我的绘制函数,该函数每次调用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;
}
You've got multiple variables called i
, and the one in the draw
function hasn't been given a var
declaration specifier so it's overwriting your timer variable. 您有多个名为i
变量,并且draw
函数中的变量没有被赋予var
声明说明符,因此它将覆盖您的timer变量。
In any event (pun not intended) you should investigate window.requestAnimationFrame
to handle your screen refreshes, and not use timers at all. 无论如何(不希望使用双关语),您应该研究window.requestAnimationFrame
来处理屏幕刷新,并且根本不使用计时器。 It'll make your game animation much smoother. 它将使您的游戏动画更加流畅。
for (i=0; i < NROWS; i++) {
it seems that variable i
has been replaced by the for
loop. 似乎变量i
已经被for
循环所取代。
Rename your interval variable name 重命名您的区间变量名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.