setInterval会漂移吗? [英] Will setInterval drift?

查看:91
本文介绍了setInterval会漂移吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真是一个非常简单的问题。如果我使用 setInterval(某事,1000),我是否可以完全确定在31天之后它会触发某事正好 60 * 60 * 24 * 31 次?或者是否存在所谓漂移的风险?

This is a pretty simple question really. If I use setInterval(something, 1000), can I be completely sure that after, say, 31 days it will have triggered "something" exactly 60*60*24*31 times? Or is there any risk for so called drifting?

推荐答案

以下是您可以在Firefox中运行的基准测试:

Here's a benchmark you can run in Firefox:

var start = +new Date();
var count = 0;
setInterval(function () {
    console.log((new Date() - start) % 1000,
    ++count,
    Math.round((new Date() - start)/1000))
}, 1000);

第一个值应尽可能接近0或1000(任何其他值显示关闭发现触发的时间是。第二个值是代码被触发的次数,第三个值是应该被触发的次数。你会注意到,如果你占用了你的CPU它可以完全离开现场,但它似乎纠正自己。尝试运行它更长的时间,看看它是如何处理的。

First value should be as close to 0 or 1000 as possible (any other value shows how "off the spot" the timing of the trigger was.) Second value is number of times the code has been triggered, and third value is how many times the could should have been triggered. You'll note that if you hog down your CPU it can get quite off the spot, but it seems to correct itself. Try to run it for a longer period of time and see how it handles.

这篇关于setInterval会漂移吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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