如何使用 javascript 在一秒钟内完成 60 次操作

How to do something 60 times in a second with javascript

我认为涉及setinterval

我有第二个用这个

var s=today.getSeconds();

然后使用setinterval

我知道了

setInterval(function(){ alert("Hello"); }, 3000);

问题...我不认为我可以将一秒除以 60 并使用它 "asynchronously" 我认为我使用这个词是正确的,一个秒单位除以 60 次,每 1/第 60 个增量发生了一些事情

我想知道我是否应该/必须使用毫秒,因为这些单位存在,我可能只是使用一个比率或其他东西来相当于一秒/六十

var time = 1000/60;  
setInterval(function(){ alert("Hello"); }, time);

1000 是毫秒除以 60。

但是这种方法有一个缺点,如果您的函数在那个时间(非常短的时间跨度)没有时间 运行,它不会等到它完成。所以它会对您的应用程序产生相当灾难性的影响。

那么递归调用 setTimeout 可能会更好,这样它会在再次调用之前完成您的函数的执行。

var time = 1000/60;  
(function loop(){
   setTimeout(function(){

      // logic here

      // recurse
      loop();

  }, time);

})();

当然,requestAnimationFrame 很好,但旧版浏览器不支持它。如果您想在旧版浏览器中使用代码,我建议您使用递归 settTimeout 方法。这将适用于任何地方!

六十分之一秒大约为 16 毫秒,因此您可以:

setInterval(function(){ alert("Hello"); }, 16);
setInterval(function(){ alert("Hello"); }, 1000/60);

正如评论中所建议的那样,由于您每秒请求 60 次,这可能意味着您想要更新动画,即更改屏幕上某些 DOM 元素的颜色、位置、形状等.

为此推荐使用 requestAnimationFrame 而不是 setInterval.

所以不用

setInterval(function () {
   doSomething();
}, 16)

使用

function myFunction () {
   doSomething();
   requestAnimationFrame(myFunction);
}
requestAnimationFrame(myFunction);

这允许浏览器执行某些优化。

来自 MDN:

You should call this method whenever you're ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation.

The callback rate may be reduced to a lower rate when running in background tabs.

名称 requestAnimationFrame 可能有点令人困惑,但您应该将其理解为 "please run my callback whenever the browser is ready to do a repaint of the screen",即您让浏览器决定确切的时间,而不是您自己强加。