setTimeout 每次被清除并再次调用时都会增加



这是我遇到的最奇怪的事情之一。

http://cabbibo.com

基本上,在我的网站上,有一堆旋转的形状。每个旋转形状在首次调用时设置超时,以使其旋转。每当访问者单击网页时,这些形状都会被清除并再次随机生成。

问题是在第二次点击时,它们的旋转速度更快。 第三次点击甚至更快,到第四次点击时,它们旋转得如此之快,以至于它们变得超级波涛汹涌和不流畅。

当使用 chrome://flags FPS 计数器观看网站时,它将以 EVEN 60 fps 的速度开始,然后当它到达第四次或第五次点击时,它将在 20 到 50 fps 之间跳跃。

代码的缩写部分如下:

//creates timeout variable OUTSIDE the timeout function, so it can be cleared
var t;
var speedRandom;
function getRandSpeed(){
    var randomSpeed = (Math.random()*.01);
    if (randomSpeed<=.001){
        randomSpeed=.001;
    }else if(randomSpeed>=.005){
        randomSpeed=.005;
    }
    console.log(randomSpeed);
    if (rightSpin==0){
        speedRandom=randomSpeed;
        rightSpin=1;
    }else{
        speedRandom=-randomSpeed;
        rightSpin=0;
    }
}
objs[whichImg].speed = speedRandom;
function rotateDrawing(whichImg){
    //This is the function that centers the object
    centerImg(whichImg);

    //translates the object to the centered point (different for each frame)
    objs[whichImg].ctx.translate(objs[whichImg].centeredX,objs[whichImg].centeredY);
    //rotates to the correct angle
    objs[whichImg].ctx.rotate(objs[whichImg].angle);
    //draws the image
    objs[whichImg].ctx.drawImage(objs[whichImg].image,0,0,objs[whichImg].height,objs[whichImg].width);
    //adds to the angle of the object
    objs[whichImg].angle+=objs[whichImg].speed;
    t=setTimeout(function(){rotateDrawing(whichImg)},40);

}
//THE ABOVE CODE WILL BE EXECUTED FOR EVERY SHAPE (TOTAL AROUND 5)

//this is what is called when the screen is clicked
function destroy(){
    functionThatClearsAllTheImages();
    clearTimeout(t);
    rotateDrawing(whichImg);
}

这段代码可能有一些漏洞,但它确实起作用,问题是在第五次点击后它是断断续续的。

如果有人需要,我可以添加更多代码,但任何建议都会非常有帮助!

问题是每次我创建一个新对象时,超时都在该创建代码中。这意味着超时被调用了 5 次,当我清除它时,它只被清除了一次。

为了解决这个问题,我创建了一个超时函数,其中包含一个循环,可以旋转形状。这意味着每次我必须清除它时,它都必须清除所有 5 个形状的循环!

最新更新