Episode 43 of 46

JavaScript Timers

Learn setTimeout and setInterval for delayed and repeated code execution.

JavaScript provides timer functions to run code after a delay or at regular intervals.

setTimeout — Run Once After a Delay

// Run after 2 seconds (2000 milliseconds)
setTimeout(function() {
    console.log("This runs after 2 seconds");
}, 2000);

// With arrow function
setTimeout(() => {
    alert("Time's up!");
}, 3000);

Canceling a Timeout

let timerId = setTimeout(() => {
    console.log("This won't run");
}, 5000);

// Cancel before it fires
clearTimeout(timerId);

setInterval — Run Repeatedly

// Run every 1 second
let count = 0;

let intervalId = setInterval(function() {
    count++;
    console.log("Count:", count);

    if (count >= 5) {
        clearInterval(intervalId);
        console.log("Stopped!");
    }
}, 1000);

Practical Example — Countdown Timer

function startCountdown(seconds) {
    let remaining = seconds;
    let display = document.querySelector("#timer");

    let interval = setInterval(function() {
        let mins = Math.floor(remaining / 60);
        let secs = remaining % 60;
        display.textContent = `${mins}:${secs.toString().padStart(2, "0")}`;

        if (remaining <= 0) {
            clearInterval(interval);
            display.textContent = "Time's up!";
        }
        remaining--;
    }, 1000);
}

startCountdown(120);  // 2-minute countdown

Practical Example — Digital Clock

function updateClock() {
    let now = new Date();
    let time = now.toLocaleTimeString();
    document.querySelector("#clock").textContent = time;
}

setInterval(updateClock, 1000);
updateClock();  // Run immediately too