JavaScript provides native timer methods on the window object to schedule code execution after a specific time delay or on a recurring periodic cadence. Timers are executed asynchronously through the browser's Web API subsystem and the Event Loop.
setTimeout(fn, delayMs) - One-Time Delay// Schedule greeting after 2.5 seconds (2500ms):
const timerId = setTimeout(() => {
console.log("2.5 seconds elapsed! Executing scheduled task.");
}, 2500);
// Canceling timer before it fires:
clearTimeout(timerId); // Prevents execution!
setInterval(fn, delayMs) - Recurring Periodic Intervallet secondsRemaining = 5;
const countdownInterval = setInterval(() => {
console.log(`Time Remaining: ${secondsRemaining}s`);
secondsRemaining--;
if (secondsRemaining < 0) {
clearInterval(countdownInterval); // Essential: stops the timer!
console.log("Timer Finished: Rocket Launch!");
}
}, 1000);
setTimeout(fn, 0)Passing 0ms does NOT execute code immediately. Instead, it defers the callback to the Macrotask Queue, forcing it to wait until all current synchronous code in the Call Stack finishes:
console.log("1. Synchronous START");
setTimeout(() => {
console.log("3. Inside setTimeout 0ms");
}, 0);
console.log("2. Synchronous END");
// Output Order:
// 1. Synchronous START
// 2. Synchronous END
// 3. Inside setTimeout 0ms
Exam Question: "Explain the output of this classic interview loop:"
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
3, 3, 3 (NOT 0, 1, 2!).var is function-scoped, a single shared i variable is hoisted. By the time the 100ms timers fire from the task queue, the synchronous loop has already completed, and i equals 3.var with let (for (let i = 0; i < 3; i++)). Because let is block-scoped, a unique binding of i is preserved for each iteration, correctly printing 0, 1, 2.
Congratulations on completing Tier 4: DOM & Browser APIs! Now let us conquer Asynchronous Programming, Promises, and Network APIs. Proceed to Tier 5: JavaScript Asynchronous Programming & Callbacks →