When set a timer by function setInterval with a certain interval (e.g 1000ms) , the execute time of the callback is another value (e.g 500ms).
The real interval between two callbacks is 1000 + 500 + 500ms.
It is more reasonable that the real interval is 1000 + 500ms.
Code example:
// function sleep mocks some real logic that executed cost a certain time.
const sleep = function (milliSeconds) {
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + milliSeconds);
};
const start = new Date();
var last = start;
var interval = setInterval(function() {
var now = new Date();
console.log('timer callback from start ' + (now - start) + 'ms ' + 'from last callback ' + (now - last) + 'ms');
last = now;
sleep(500);
}, 1000);
The output is something like this:
timer callback from start 1537ms from last callback 1537ms
timer callback from start 3540ms from last callback 2003ms
timer callback from start 5543ms from last callback 2003ms
timer callback from start 7545ms from last callback 2002ms
timer callback from start 9546ms from last callback 2001ms
timer callback from start 11548ms from last callback 2002ms
timer callback from start 13549ms from last callback 2001ms
timer callback from start 15550ms from last callback 2001ms
When change the logic of listOnTimeout:
function listOnTimeout() {
var msecs = this.msecs;
var list = this;
debug('timeout callback %d', msecs);
var now = Timer.now();
debug('now: %s', now);
var diff, first, threw;
while (first = L.peek(list)) {
diff = now - first._idleStart;
if (diff < msecs) {
list.start(msecs - diff, 0); =====>>>>> list.start(msecs, 0);
debug('%d list wait because diff is %d', msecs, diff);
return;
} else {
...
The output of the code example:
timer callback from start 1703ms from last callback 1703ms
timer callback from start 3207ms from last callback 1504ms
timer callback from start 4707ms from last callback 1500ms
timer callback from start 6207ms from last callback 1500ms
timer callback from start 7708ms from last callback 1501ms
timer callback from start 9210ms from last callback 1502ms
timer callback from start 10711ms from last callback 1501ms
When set a timer by function
setIntervalwith a certain interval (e.g 1000ms) , the execute time of the callback is another value (e.g 500ms).The real interval between two callbacks is 1000 + 500 + 500ms.
It is more reasonable that the real interval is 1000 + 500ms.
Code example:
The output is something like this:
When change the logic of listOnTimeout:
The output of the code example: