【问题标题】:JS run function with perfect intervalJS以完美间隔运行函数
【发布时间】:2021-05-31 07:21:48
【问题描述】:

我想每 25 毫秒运行一次命令。 setIntervalsetTimeout 的问题在于它们并不是每 25 毫秒运行一次。如何使间隔准确?

【问题讨论】:

  • 也许可以试试 requestAnimationFrame
  • setInterval 和 setTimeout 不可能做到完美。
  • 现代消费者操作系统不支持你想要的。
  • 您可以使用 setImmediate 并尝试通过查看日期差异来尽可能接近它,但它仍然不会 100% 准确,因为它仍然只是安排它运行下一个可用时间。
  • Jake 和 Surma 最近做了一个关于计时器的视频:youtu.be/MCi6AZMkxcU

标签: javascript node.js


【解决方案1】:

您可以尝试使用requestAnimationFrame 方法。它是一个简单的基于轮询的循环,适合像您自己一样开发游戏。

你可以使用这个有点粗略的实现。

const element = document.getElementById('some-element-you-want-to-animate');
let start;
let cycleCount = 0;

// Set this variable to true when you want to end the loop
let cyclesSetToEnd = false;

// Define the resolution per cycle.
// Number of 1ms cycles after which doSomething is executed.
const resolutionFactor = 25000;

function step(timestamp) {
  if (start === undefined)
    start = timestamp;
  const elapsed = timestamp - start;

  // Check if elapsed time has hit a second
  if (elapsed % resolutionTime > cycleCount) {
    cycleCount = elapsed % resolutionTime;
    // Do time-sensitive update here
    doSomething();
  }

  if (!cyclesSetToEnd) { // Stop the animation after 20 seconds
    window.requestAnimationFrame(step);
  }
}

window.requestAnimationFrame(step);

传递给step 方法的时间戳是DOMHighResTimestamp 其中

...应该以毫秒为单位表示时间,精确到 5 微秒...

注意

如果用户代理由于硬件或软件限制而无法提供精确到 5 微秒的时间值,则用户代理可以将 DOMHighResTimeStamp 表示为精确到毫秒的毫秒时间。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多