In JS, if you intend to use setinterval for reciprocal, timing and other functions, often inaccurate, because the setinterval callback function is not immediately after the execution, But wait until the system calculates the resource is idle to execute. The next trigger time is to start the timer after the setinterval callback function has finished executing, so if the computations performed within the setinterval are too time-consuming, or if there are other time-consuming tasks executing, The timing of the setinterval will be more and more inaccurate and the delay is severe.
The following code illustrates the 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 number of delay milliseconds that the SetInterval trigger time and the correct trigger time are output in the code
176
495
652
807
961
1114
1268 1425 1579 1734 1888
2048
2201
2357
2521 2679 2834
...
You can see that the delay is getting worse.
Back to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/
In order to use the 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 time of the next trigger is calculated by subtracting the current time and the exact time gap by 1000 (i.e. cycle time), thus correcting the current trigger delay.
Here is the output
186
230
271
158
899
900
899
900 899 899
899
418
232
266
145
174 902 214 242 268 149
179
214
...
It can be seen that although the trigger time is not absolutely accurate, but because each trigger is corrected in time, so did not cause error accumulation.
Author: cnblogs Little Night Clifford