I think the first time is not calculated from the start interval in the queue, but from where you set startTime.
Then the first timer counts the initialization time, the creation of the environment, the distribution of variables and timers.
Try this modification:
var limit = 1000000000; var intervals = 0; var totalTime = new Date(); var startTime = false; var uid = setInterval( function () { if (!startTime) startTime = new Date();
In addition, the first time takes longer because the function is interpreted, then the subsequent times are executed by the โcompiledโ / optimized Javascript JIT (see https://en.wikipedia.org/wiki/Just-in-time_compilation ). Check this code to see the proof.
var limit = 1000000000; var intervals = 0; var totalTime = new Date(); var startTime = new Date(); var uid = setInterval( function () { startTime = new Date();
output:
Interval 1 Time elapsed : 3249 Interval 2 Time elapsed : 299 Interval 3 Time elapsed : 31 Interval 4 Time elapsed : 5 Interval 5 Time elapsed : 0 Interval 6 Time elapsed : 0 Interval 7 Time elapsed : 0 Interval 8 Time elapsed : 0 Interval 9 Time elapsed : 0 Interval 10 Time elapsed : 0
setInterval is not suitable for measuring the time during which it should queue the next execution. I think this is due to sleep () ing. This is unreliable if the process accepts the processor and hangs it (as for you).
setInterval guarantees only the following:
- Run number 1 will not execute in less than 250 ms.
- Execution number 2 will not occur less than 2 * 250 m ahead.
- Run number 3 will not happen in less than 3 * 250 m.
- ...
setInterval does not guarantee that any execution will occur before a certain time in the future. It depends on the current CPU usage.
The queue and the start of functions in the queue also depend on the current CPU usage.
Additional General Tips If you need to perform a function periodically, I recommend this approach, which guarantees a delay that always exceeds 250 ms between execution
var t = false; var fun = function() { console.log("run"); t = setTimeout(fun, 250); } fun();
jperelli
source share