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

JavaScript, setInterval() working beyond its timer

本文关键字:计时器 工作 setInterval JavaScript      更新时间:2023-09-26

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

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

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

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

编辑:(从注释复制/粘贴)如果我的函数的限制是每秒20帧(用于计算),但我的setInterval以每秒30帧运行,它会以20帧运行吗?(与同时运行的两个功能相反)

Javascript是单线程的,因此您对设置间隔的调用将添加到队列中。它们将按顺序执行,但如果函数的执行时间比实际间隔长,则工作时间将超过setInterval调用的预期完成时间。

请改用requestAnimationFrame。。这不会占用你的cpu。

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

RequestAnimationFrame工作巧妙,允许您在不加重浏览器负担的情况下操纵帧速率。

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

链接-->用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);
    }

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

最好试试这个

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