The Timer module exposes global APIs for scheduling functions to be called at some future period of time. Because the timer functions are global, you do not need to require('timers') to use them.
These are the exact same scheduling functions you likely already know from front-end JavaScript!
setTimeout(): Executes a callback function once after a specified delay (in milliseconds).setInterval(): Repeatedly executes a callback function with a fixed time delay between each call.
// Run once after 2000 milliseconds (2 seconds)
setTimeout(() => {
console.log('Two seconds have passed!');
}, 2000);
// Run repeatedly every 1000 milliseconds (1 second)
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log('Ping ' + count);
// Stop the interval after 3 pings
if (count === 3) {
clearInterval(intervalId);
console.log('Interval stopped.');
}
}, 1000);
The backend features a unique timer called setImmediate(). It executes a given callback function immediately after the current event loop cycle finishes its initial phases. It operates faster than setTimeout(callback, 0).
setImmediate(() => {
console.log('This runs immediately after the current phase!');
});
Which function should you use to execute code repeatedly at a fixed interval?