In js, if you plan to use setInterval for countdown, timing and other functions, it is often inaccurate, because the callback function of setInterval is not executed immediately after the time is up, but will be executed after the system computing resources are idle. And the next trigger Time starts counting after the setInterval callback function is executed, so if the calculations performed within setInterval are too time-consuming, or there are other time-consuming tasks being performed, the timing of setInterval will become increasingly inaccurate and the delay will be severe.
The following code can illustrate this problem
var startTime = new Date().getTime();
var count = 0;
//Time-consuming task
setInterval(function(){
var i = 0;
while(i < 100000000);
}, 0);
setInterval(function(){
count ;
console.log(new Date().getTime() - (startTime count * 1000)) ;
}, 1000);
The code outputs the setInterval trigger time and the delay in milliseconds that should be the correct trigger time
176
340
495
652
807
961
1114
1268
1425
1579
1734
1888
2048
2201
2357
2521
2679
2834
2996
.. ....
You can see that the delay is getting more and more serious.
In order to use a relatively accurate timing function in js, we can
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);
console.log(new Date().getTime() - (startTime count * 1000));
}
setTimeout(fixed, 1000);
In the code, the difference between the current time and the accurate time is subtracted from 1000 (that is, the cycle time) to calculate the next trigger time, thereby correcting the current trigger delay.
Below is the output
186
200
230
271
158
899
900
899
900
899
899
899
902
899
418
202
232
266
145
174
192
214
242
268
149
179
214
. .....
It can be seen that although the trigger time is not absolutely accurate, since each trigger is corrected in time, there is no accumulation of errors.