JavaScript Timers and the Event Loop
A timer is a request to run code after a delay. The event loop still runs the timer only when the call stack is empty.
setTimeout with zero delay
A delay of 0 does not mean at once. The callback still waits for the main script to finish.
console.log("A");
setTimeout(() => { console.log("B"); }, 0);
console.log("C");A repeating timer
setInterval runs the callback again after each delay. clearInterval stops it after the third tick.
let count = 0;
const id = setInterval(() => {
count = count + 1;
console.log("Tick " + count);
if (count === 3) { clearInterval(id); }
}, 50);Cancelling a timer
clearTimeout cancels a timer before it runs. The cancelled callback prints nothing.
const id = setTimeout(() => { console.log("Never printed"); }, 50);
clearTimeout(id);
console.log("Timer cancelled");Example
console.log("Start");
setTimeout(() => { console.log("Short wait"); }, 10);
setTimeout(() => { console.log("Long wait"); }, 50);
console.log("End");Key points
- setTimeout: a function that runs one callback after a delay in milliseconds
- A delay of 0 still waits for the call stack to clear.
- setInterval: a function that repeats one callback after each delay
- clearTimeout: a function that cancels a timer before it runs
- clearInterval: a function that stops a repeating timer
In this example, the first line prints Start. Both timers wait in the queue while the main script runs. The 10 millisecond timer fires before the 50 millisecond timer.
Note
A timer delay is the shortest wait, not the exact time.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does setTimeout with a delay of 0 do?