Home >Web Front-end >JS Tutorial >Solution to the problem of inaccurate setInterval timer_javascript skills

Solution to the problem of inaccurate setInterval timer_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:49:102357browse

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

Copy the code The code is as follows:

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
Copy Code The code is as follows:

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
Copy code The code 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 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
Copy code The code 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, there is no accumulation of errors.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn