Timers

Schedule code to run later with setTimeout and setInterval.

Syntaxconst id = setInterval(fn, 1000); clearInterval(id);

Node provides timer functions to run code in the future:

  • setTimeout(fn, ms) — run fn once after a delay.
  • setInterval(fn, ms) — run fn repeatedly every interval.
  • clearTimeout / clearInterval — cancel a timer.

Each timer function returns a handle you can pass to the matching clear function to stop it.

Example

Example · javascript
let count = 0;
const id = setInterval(() => {
  count++;
  console.log('Tick', count);
  if (count === 3) {
    clearInterval(id);
    console.log('Done');
  }
}, 1000);

When to use it

  • A rate-limiter uses `setInterval` to reset a request counter every 60 seconds, ensuring no client exceeds the allowed quota per minute.
  • A server health-check pings a downstream service every 30 seconds with `setInterval` and logs latency trends over time.
  • A deployment script uses `setTimeout` to give a newly started container 5 seconds to warm up before sending traffic its way.

More examples

setTimeout and clearTimeout

Schedules a one-time callback after a delay and shows how to cancel it with `clearTimeout`.

Example · js
const handle = setTimeout(() => {
  console.log('Fired after 2 seconds');
}, 2000);

// Cancel it before it fires (if needed)
// clearTimeout(handle);

setInterval for repeated tasks

Runs a function every second and stops after 5 iterations using `clearInterval`.

Example · js
let count = 0;
const id = setInterval(() => {
  count++;
  console.log('Tick', count);
  if (count === 5) clearInterval(id); // stop after 5 ticks
}, 1000);

setImmediate vs setTimeout(0)

Compares `setImmediate` and `setTimeout(fn, 0)` to illustrate their position in the event loop.

Example · js
setImmediate(() => console.log('setImmediate'));
setTimeout(() => console.log('setTimeout 0'), 0);
console.log('sync');
// Output: sync -> setTimeout 0 OR setImmediate (order varies)
// Inside an I/O callback, setImmediate always fires first

Discussion

  • Be the first to comment on this lesson.