Timer latency
JS Timer
When setTimeout and setinterval functions are used, the time interval t set for the second parameter is from the time when this function (setTimeout (F1, T) and setinterval (F1, t) are called, after T ms, F1 is added to the UI task queue, but not necessarily executed, especially when other tasks are executed during this period, there may be a time delay. Therefore, when you use the setinterval function to create a timer, a delay occurs.
var startTime = new Date().getTime();
var count = 0;
/*setInterval(function(){
var i = 0;
while(i++ < 100000000);
}, 0);*/
function fixed() {
count++;
var offset = new Date().getTime() - (startTime + count * 1000);
var nextTime = 1000 - offset;
if (nextTime < 0) nextTime = 0;
SetTimeout (fixed, nexttime); // corrected the latency
console.log(new Date().getTime() - (startTime + count * 1000));
}
setTimeout(fixed, 1000);
Setinterval timer latency