【问题标题】:setTimeout increases everytime it is cleared and called againsetTimeout 每次被清除并再次调用时都会增加
【发布时间】:2012-08-13 16:01:34
【问题描述】:

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

http://cabbibo.com

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

问题在于,在第二次点击时,它们会旋转得更快一些。第三次点击时甚至更快,到第四次点击时,它们旋转得如此之快,以至于它们变得非常不稳定和不流畅。

当使用 chrome://flags FPS 计数器观看网站时,它会以 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 次的对象内部吗?如果没有,您可能会为所有形状重用t 变量,因此在调用destroy 时只清除一个超时,因为t 在它们之间共享。
  • @TheZ 你完全正确!重写了超时,使其包含 5 个对象,而不是为每个对象设置一个新的超时(这实际上是相同的超时变量。)我不知道如何表明你为我回答了这个问题!但你做到了。

标签: javascript animation canvas settimeout timing


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2019-05-12
    • 2013-03-10
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2016-12-24
    相关资源
    最近更新 更多