Timers
Schedule code to run later with setTimeout and setInterval.
Syntax
const id = setInterval(fn, 1000);
clearInterval(id);Node provides timer functions to run code in the future:
setTimeout(fn, ms)— runfnonce after a delay.setInterval(fn, ms)— runfnrepeatedly 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
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`.
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`.
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.
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