JavaScript,setInterval()在其计时器之外工作

时间:2013-08-02 07:04:20

标签: javascript setinterval

我有一个使用setInterval()调用的函数,如下所示:

canvasInterval = setInterval(updateCGoL, (1000/this.frameRate)|0);

我允许用户指定每秒的帧数(有限制,只有parseInt()后的非NaN值为Math.max(Math.min(用户输入, 30), 1))。即使它以每秒30帧的速度运行,我也很确定它在下一帧之前完成了它的工作。我的问题是:

  • 如果在一段时间内没有完成工作,会发生什么 我给了它?
  • 有没有办法测试它是否在下一次之前没有完成它的工作 框架,如果这是一个问题吗?

编辑 :(从评论中复制/粘贴)如果我的功能限制为每秒20帧(计算),但我的setInterval以每秒30帧的速度运行,那么它将以20帧的速度运行? (与两个同时运行的函数相反)

3 个答案:

答案 0 :(得分:2)

Javascript是单线程的,因此您对set interval的调用将被添加到队列中。它们将按顺序执行,但如果您的功能花费的时间超过实际间隔时间,则会超出setInterval来电的预期结束时间。

答案 1 :(得分:2)

使用 requestAnimationFrame 代替..这不会占用你的cpu。

简单来说,setInterval没有能力与我们的cpu进行交互,并且不必要地最终会使你的调用排队并浪费大量的cpu周期

RequestAnimationFrame工作巧妙,允许您操纵帧速率而不会给浏览器带来负担。

我刚刚回答了类似的问题。

LINK - > Replace setinterval by RAF

它有一个初学者应该遵循的所有链接!!!

而不是清除间隔使用cancelAnimationFrame

只是你应该如何处理事情的片段。最终是一个更好的解决方案。

// This makes sure that there is a method to request a callback to update the graphics for next frame
    requestAnimationFrame =
    window.requestAnimationFrame || // According to the standard
    window.mozRequestAnimationFrame || // For mozilla
    window.webkitRequestAnimationFrame || // For webkit
    window.msRequestAnimationFrame || // For ie
    function (f) { window.setTimeout(function () { f(Date.now()); }, 1000/60); }; // If everthing else fails


var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;//for cancellation
// some code here

var progress = 0

function doSomething(){
    if (progress != 100){
        // do some thing here
        var myAnimation = requestAnimationFrame(doSomething)      
    }else{
       // dont use clearInterval(interval) instead when you know that animation is completed,use cancelAnimationFrame().
       window.cancelAnimationFrame(myAnimation);
    }

答案 2 :(得分:0)

我不知道你的frameRate是什么。如果用户输入,请在那里进行一些验证。所以你有更好的价值。

最好试试这个

var timeRate = this.frameRate? 1000/parseInt(this.frameRate) : 0;
canvasInterval = setInterval(updateCGoL, timeRate);