当我调用一次函数时,间隔是可以的,它会按预期添加和清除。当再次调用同一函数时,该间隔会被调用数百次。我该如何阻止这种行为?我的功能出了什么问题?
function draw(){
ctx.clearRect(0,0,width,height);
ctx.fillStyle = 'blue';
// Add cube width 5px
if(cube.width <= 300){
cube.width += 5;
}
// Draw it on the screen
ctx.fillRect(cube.x,cube.y,cube.width,cube.height);
// Create function b(e) to check cubes collision
function b(e){
var x = e.clientX - ctx.canvas.offsetLeft;
var y = e.clientY - ctx.canvas.offsetTop;
if(x >= cube.x && x <= cube.x + cube.width
&& y >= cube.y && y <= cube.y + cube.height){
ctx.canvas.removeEventListener('click',b,false);
level1();
return;
}
}
ctx.canvas.addEventListener('click', b, false);
// Set the interval to 60 FPS
var timer = setInterval(function(){
check += 1;
console.log(check);
if(check > 50){
return;
}
// Call again the same function
draw();
},1000/60);
}
我怀疑这是一个javascript问题,所以我猜测canvas与此无关。
更新我调用draw的函数(位于另一个函数内部):
function a(e){
var x = e.clientX - ctx.canvas.offsetLeft;
var y = e.clientY - ctx.canvas.offsetTop;
if(x >= player.x && x <= player.x + player.width
&& y >= player.y && y <= player.y + player.height){
ctx.canvas.removeEventListener('click',a,false);
draw();
}
}
// Add the click event using the previous function
ctx.canvas.addEventListener('click', a, false);
根据我的理解,我发布了这个答案
function draw(check){
ctx.clearRect(0,0,width,height);
ctx.fillStyle = 'blue';
// Add cube width 5px
if(cube.width <= 300){
cube.width += 5;
}
// Draw it on the screen
ctx.fillRect(cube.x,cube.y,cube.width,cube.height);
// Create function b(e) to check cubes collision
function b(e){
var x = e.clientX - ctx.canvas.offsetLeft;
var y = e.clientY - ctx.canvas.offsetTop;
if(x >= cube.x && x <= cube.x + cube.width
&& y >= cube.y && y <= cube.y + cube.height){
ctx.canvas.removeEventListener('click',b,false);
level1();
return;
}
}
ctx.canvas.addEventListener('click', b, false);
check+ = 1;
if(check <=50)
{
// Set the interval to 60 FPS
var timer = setTimeout(function()
{
// Call again the same function
draw(check);
},1000/60);
}
}
更新我调用draw的函数(在另一个函数中):
function a(e){
var x = e.clientX - ctx.canvas.offsetLeft;
var y = e.clientY - ctx.canvas.offsetTop;
if(x >= player.x && x <= player.x + player.width
&& y >= player.y && y <= player.y + player.height){
ctx.canvas.removeEventListener('click',a,false);
var check = 0;
draw(check);
}
}
// Add the click event using the previous function
ctx.canvas.addEventListener('click', a, false);
在从其他函数调用draw函数之前,您可以在外部的某个地方声明检查变量并将其设置为0,也可以将初始值为您想要的值的检查变量传递给draw函数
您应该只调用setInterval()
一次,并且在draw函数之外。按照这种方式,您启动了越来越多的计时器,导致draw()
函数被调用的次数无限增加。或者:"要在指定的毫秒数后只执行一次函数,请使用setTimeout()
方法"。参考:Window setInterval。setTimeout()
可以在draw()
函数中使用。