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 reached, but will not be executed until the system's computing resources are idle. The next trigger time is not started after the setInterval callback function is executed. Therefore, if the calculations executed in setInterval are too time-consuming, or there are other time-consuming tasks being executed, the timing of setInterval will become increasingly inaccurate and has a very serious delay.
The following code can illustrate this problem
The code copy is as follows:
var startTime = new Date().getTime();
var count = 0;
//Time-consuming tasks
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 milliseconds that should be triggered correctly.
The code copy is as follows:
176
340
495
652
807
961
1114
1268
1425
1579
1734
1888
2048
2201
2357
2521
2679
2834
2996
......
It can be seen that the delay is getting worse and worse.
In order to use relatively accurate timing functions in js, we can
The code copy is as follows:
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 gap between the current time and the accurate time is calculated by subtracting 1000 (that is, the period time), thereby correcting the delay of the current trigger.
Below is the output
The code copy is as follows:
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, no error accumulation is caused.