简体   繁体   中英

Why does the setTimeout timer fire twice?

I have a Timeout timer that fires on the minute based on the system clock. The thing I don't understand is why it fires twice every minute? If you check the console log it fires 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();

this is the console log:

在此处输入图片说明

It is most likely an issue with javascript timers not being very accurate, you could try something like this instead:
http://fiddle.jshell.net/7ffv00jy/

where the big change is that you test to see if the timeUntilNextTick is very small, then you should wait a full more minute (since you probably just fired one of these events anyways..)
You could also have a timeout to find the first minute, then have that "starter" function set up an interval instead.

Here is the changed code:

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();

so far it has given me this:

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  

(The important part here is the date time at the beginning which, with the exception of the "starter" all ends with :00 seconds (if you print the ms part they would probably not all end with .00000))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM