⏱ Day 15 — setTimeout, setInterval & Timers in JavaScript

⏱ Day 15 — setTimeout, setInterval & Timers in JavaScript

Hi Guys Welcome to Day 15 ⚡ Today we’ll explore how JavaScript manages **time-based actions** — delaying code, running things repeatedly, and stopping them gracefully. This is essential for animations, notifications, auto-refreshing dashboards, and countdown timers.

🧩 1️⃣ setTimeout()

Executes a function **once** after a given time (in milliseconds).

setTimeout(() => {
  console.log("This runs after 2 seconds");
}, 2000);

🔁 2️⃣ setInterval()

Executes a function **repeatedly** at specified intervals.

let count = 1;
let timer = setInterval(() => {
  console.log("Count:", count);
  count++;
  if (count > 5) clearInterval(timer);
}, 1000);

🛑 3️⃣ clearTimeout() & clearInterval()

Use these to stop running timers.

let reminder = setTimeout(() => {
  console.log("Time's up!");
}, 5000);

clearTimeout(reminder); // Stops before executing

🎯 4️⃣ Real-World Example — Countdown Timer

let time = 5;
let countdown = setInterval(() => {
  console.log(time);
  time--;
  if (time < 0) {
    console.log("Blast Off!");
    clearInterval(countdown);
  }
}, 1000);

🧠 5️⃣ Practice Task

  1. Create a message that appears after 3 seconds using setTimeout().
  2. Build a timer that prints numbers 1 to 10 using setInterval().
  3. Stop the timer when a condition is met using clearInterval().

🎯 Summary

Timers make JavaScript capable of handling real-time behaviors like reminders, progress bars, and animations. Next, you’ll move to **Working with JSON and APIs**, connecting your JS to live data sources — an exciting step toward building full-stack projects.

Comments