setInterval计时缓慢偏离准确 [英] setInterval timing slowly drifts away from staying accurate

查看:1228
本文介绍了setInterval计时缓慢偏离准确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎当我 setInterval 1000ms时,它实际上每1001ms左右触发一次该函数。这导致时间漂移缓慢,其运行时间越长。

It seems that when I setInterval for 1000ms, it actually fires the function every 1001ms or so. This results in a slow temporal drift the longer its running.

var start;
var f = function() {
    if (!start) start = new Date().getTime();
    var diff = new Date().getTime() - start;
    var drift = diff % 1000;
    $('<li>').text(drift + "ms").appendTo('#results');
};

setInterval(f, 1000);

运行时会立即显示不准确信息。

When run this shows the inaccuracy immediately.


  • 0ms

  • 1ms

  • 2ms

  • 3ms

  • 4ms

  • 5ms

  • 5ms

  • 7ms

  • 8ms

  • 9ms

  • 9ms

  • 10ms

  • 0ms
  • 1ms
  • 2ms
  • 3ms
  • 4ms
  • 5ms
  • 5ms
  • 7ms
  • 8ms
  • 9ms
  • 9ms
  • 10ms

自己看看: http://jsfiddle.net/zryNf/

那么有更准确的方法来保持时间吗?或者一种使 setInterval 表现得更准确的方法?

So is there a more accurate way to keep time? or a way to make setInterval behave with more accuracy?

推荐答案

我我想我可能已经找到了解决方案。我想,如果你可以测量它,你可以补偿它,对吗?

I think I may have figured out a solution. I figured, if you can measure it you can compensate for it, right?

http://jsfiddle.net/zryNf/9/

var start;
var nextAt;

var f = function() {
    if (!start) {
        start = new Date().getTime();
        nextAt = start;
    }
    nextAt += 1000;

    var drift = (new Date().getTime() - start) % 1000;    
    $('<li>').text(drift + "ms").appendTo('#results');

    setTimeout(f, nextAt - new Date().getTime());
};

f();

结果略有不同但这是最近的一次运行:

result varies a bit but here's a recent run:

0ms
7ms
2ms
1ms
1ms
1ms
2ms
1ms
1ms
1ms

因此,如果它被调用1ms,2ms甚至10ms之后它应该安排下一个电话来弥补这一点。只要每次通话都不准确,但时钟永远不会浪费时间,那么这应该可以正常工作。

So if it gets called 1ms, 2ms or even 10ms later than it should the next call is scheduled to compensate for that. As long as inaccuracy is only per call, but the clock should never lose time, then this should work well.

现在我把它包装成一个全局 accurateInterval 函数,这个函数几乎可以代替 setInterval https://gist.github.com/1d99b3cd81d610ac7351

And now I wrapped this up a global accurateInterval function which is a near drop in replacement for setInterval. https://gist.github.com/1d99b3cd81d610ac7351

这篇关于setInterval计时缓慢偏离准确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆