Timer Module

Timer Module

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!


1. setTimeout and setInterval

Basic Timers

// 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);


2. setImmediate

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!');
});

Exercise

?

Which function should you use to execute code repeatedly at a fixed interval?