setTimeout, setInterval, & Event Loop TimersJavaScript timing functions delay execution or execute callbacks periodically. setTimeout schedules a callback after a specified delay, while setInterval repeatedly executes a callback until cleared.
flowchart TD
Call["setTimeout(fn, delayMs) Called"] --> WebAPI["Web API Timer Subsystem"]
WebAPI -->|Delay Expires| TaskQueue["Task Queue (Macrotask)"]
TaskQueue -->|Call Stack Empty| EventLoop["Event Loop Pushes Callback to Call Stack"]
EventLoop --> Execute["Execute Timer Callback"]
| Function | Action | Return Value | Cancellation Method |
|---|---|---|---|
setTimeout(fn, delay) |
Executes fn once after delay ms. |
Numeric timeoutId |
clearTimeout(timeoutId) |
setInterval(fn, delay) |
Executes fn repeatedly every delay ms. |
Numeric intervalId |
clearInterval(intervalId) |
// Demonstrating setTimeout, setInterval, and timer cancellation
// 1. Delayed Execution with setTimeout
console.log("1. Script Started");
const timeoutId = setTimeout(() => {
console.log("3. setTimeout Executed after 100ms!");
}, 100);
console.log("2. Script Continued (Non-blocking)");
// 2. Periodic Execution with setInterval and Clearing
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Periodic Interval Tick #${count}`);
if (count >= 3) {
console.log("Stopping Interval...");
clearInterval(intervalId); // Stop timer repetition!
}
}, 50);
// 3. Minimum Delay (0ms) Delays to Next Event Loop Macrotask Tick
setTimeout(() => {
console.log("4. setTimeout 0ms executed after synchronous stack clears.");
}, 0);
clearTimeout(id) or clearInterval(id) when components unmount to prevent memory leaks.setTimeout Over setInterval: Prefer recursive setTimeout() for polling tasks. setInterval can queue back-to-back executions if the callback takes longer than the interval delay.0ms) is Not Instant: setTimeout(fn, 0) schedules the callback for the next event loop macrotask iteration after current synchronous code completes.Explain why setTimeout(fn, 0) executes AFTER synchronous code placed below it in the source file.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.