JavaScript Timers: Delayed Execution, Periodic Intervals & Animations

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.

1. 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!

2. setInterval(fn, delayMs) - Recurring Periodic Interval

let 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);

3. The Zero-Delay Trick: 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

University Exam Corner (BCA Examination Notes)

Exam Question: "Explain the output of this classic interview loop:"

for (var i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 100);
}
Output: Prints 3, 3, 3 (NOT 0, 1, 2!).
Explanation: Because 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.
Solution: Replace 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.

Next Step

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 →

Explore Related JavaScript Tutorials

Accelerate your JavaScript mastery by studying these tightly connected core tutorials:

Event Loop & Timers →

How timer callbacks execute in the macrotask queue.

Asynchronous Fundamentals →

Non-blocking concurrency in JavaScript.

BOM Window APIs →

Window timer methods and interval clearance.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!