[英]Why does setTimeout fire twice in Chrome, but not IE or Firefox?
[英]Why does the setTimeout timer fire twice?
我有一个超时计时器,它根据系统时钟在分钟内触发。 我不明白的是为什么它每分钟触发两次? 如果您检查控制台日志,则会触发两次http://jsbin.com/vises/3/
function runClock() {
var now = new Date();
var timeToNextTick = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
console.log((60 - now.getSeconds()* 1000)- now.getMilliseconds());
setTimeout(runClock, timeToNextTick);
}
// start it
runClock();
这是控制台日志:
javascript计时器不是很准确,这很可能是一个问题,您可以尝试使用以下方法:
http://fiddle.jshell.net/7ffv00jy/
最大的变化是您要测试timeUntilNextTick是否很小,然后您应该等待一整分钟(因为无论如何您可能都触发了其中一个事件。)
您也可能会有超时时间来查找第一分钟,然后让“启动器”功能设置一个间隔。
这是更改后的代码:
function runClock() {
var timeToNextTick = msUntilNextMinuteTick();
if(timeToNextTick < 100)
timeToNextTick += 60*1000; // Add a full minute to this..
console.log(new Date().toString() + ": " + timeToNextTick);
setTimeout(runClock, timeToNextTick);
}
// Separate function, makes it easier to debug
function msUntilNextMinuteTick(){
var now = new Date();
return (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
}
// start it
runClock();
到目前为止,它已经给了我:
Wed Oct 15 2014 13:36:22 GMT+0200 (W. Europe Summer Time): 37035
Wed Oct 15 2014 13:37:00 GMT+0200 (W. Europe Summer Time): 59790
Wed Oct 15 2014 13:38:00 GMT+0200 (W. Europe Summer Time): 59789
Wed Oct 15 2014 13:39:00 GMT+0200 (W. Europe Summer Time): 59789
Wed Oct 15 2014 13:40:00 GMT+0200 (W. Europe Summer Time): 59789
(这里重要的部分是开始的日期时间,除了“启动器”以外,所有时间都以:00秒结尾(如果打印ms部分,则它们可能不会全部以.00000结尾)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.