console.log
'1' after 1 second,
'2' after 2 seconds and
'3' after 3 seconds after start of the program.
The delay parameter only guarantees that your callback will not execute before that time has elapsed. Other queued tasks or operations could delay it further than the specified time.
const startTime = process.hrtime();
console.log('startTime: ', startTime);
for (let i = 1; i < 4; i++) {
setTimeout(() => {
console.log('Message ' + i + ' ', process.hrtime());
}, i * 1000);
}
startTime: [ 20341, 488209050 ]
Message 1 [ 20342, 499922394 ]
Message 2 [ 20343, 498388755 ]
Message 3 [ 20344, 498487014 ]
console.log('startTime: ', startTime);
for (let i = 1; i < 4; i++) {
setTimeout(() => {
console.log('Message ' + i + ' ', process.hrtime(startTime));
}, i * 1000);
}
startTime: [ 20482, 505385747 ]
Message 1 [ 1, 13938178 ]
Message 2 [ 2, 13741552 ]
Message 3 [ 3, 13861540 ]
for (let i = 1; i < 4; i++) {
setTimeout(() => {
console.log('Message ' + i + ' ', process.uptime());
}, i * 1000);
}
Message 1 1.10126115
Message 2 2.102194643
Message 3 3.102512365
const startTime = process.hrtime();
console.log('startTime: ', startTime);
let i = 1;
const interval = setInterval(() => {
console.log('Message ' + i + ' ', process.hrtime());
i++;
if (i > 3) {
clearInterval(interval);
}
}, 1000);
startTime: [ 21511, 206821155 ]
Message 1 [ 21512, 217929990 ]
Message 2 [ 21513, 218730640 ]
Message 3 [ 21514, 218790140 ]
const startTime = process.hrtime();
console.log('startTime: ', startTime);
let i = 1;
const interval = setInterval(() => {
console.log('Message ' + i + ' ', process.hrtime(startTime));
i++;
if (i > 3) {
clearInterval(interval);
}
}, 1000);
startTime: [ 21356, 295521886 ] Message 1 [ 1, 10849822 ] Message 2 [ 2, 11730624 ] Message 3 [ 3, 14871246 ]
let i = 1;
const interval = setInterval(() => {
console.log('Message ' + i + ' ', process.uptime());
i++;
if (i > 3) {
clearInterval(interval);
}
}, 1000);
Message 1 1.094841971
Message 2 2.09636721
Message 3 3.098306832
setImmediate & Date.now()
Output
Message 1 1.102803835
Message 2 2.109794804
Message 3 3.109743866