«Back to Home

Learn JavaScript

Topics

Timers — setTimeout and setInterval

Timers allow you to schedule code to run later or repeatedly after a specific amount of time.

JavaScript provides two main timer functions:

  • setTimeout() ? runs code once after a delay

  • setInterval() ? runs code repeatedly after a delay

Timers are commonly used in:

  • Pop-up messages

  • Loading screens

  • Sliders and animations

  • Countdown timers

  • Auto-refresh features

  • Notifications

  • Delayed actions

This guide explains both timers with simple, practical examples.

1. setTimeout()

Runs a function once after a specified time (in milliseconds).

Syntax:

setTimeout(function, timeInMs);

Example 1: Basic use of setTimeout

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

Output:
Hello after 2 seconds

Example 2: Delayed Notification

console.log("Loading...");

setTimeout(() => {
    console.log("Welcome!");
}, 3000);

Example 3: Passing Arguments

function greet(name) {
    console.log("Hello", name);
}

setTimeout(greet, 1500, "Aman");

2. Clearing a setTimeout()

Use clearTimeout() to stop a timeout before it runs.

let timer = setTimeout(() => {
    console.log("This will not run");
}, 2000);

clearTimeout(timer);

3. setInterval()

Runs code repeatedly after a fixed delay.

Syntax:

setInterval(function, timeInMs);

Example 1: Repeating Message

setInterval(() => {
    console.log("Repeating message");
}, 1000);

Output:
Repeating message every second

Example 2: Simple Counter

let count = 1;

setInterval(() => {
    console.log(count);
    count++;
}, 1000);

4. Clearing setInterval()

Use clearInterval() to stop repeated execution.

let counter = setInterval(() => {
    console.log("Running...");
}, 1000);

setTimeout(() => {
    clearInterval(counter);
    console.log("Stopped");
}, 5000);

Output:
Running... (repeats)
Stopped (after 5 seconds)

5. Real-Life Example: Countdown Timer

let time = 5;

let timer = setInterval(() => {
    console.log("Time left:", time);
    time--;

    if (time < 0) {
        clearInterval(timer);
        console.log("Time's up!");
    }
}, 1000);

6. Real-Life Example: Auto-Refreshing Data

function fetchData() {
    console.log("Data refreshed at", new Date().toLocaleTimeString());
}

setInterval(fetchData, 3000);

Runs every 3 seconds.

7. Real-Life Example: Hiding a Message After 3 Seconds

HTML:

<p id="msg">This message will disappear</p>

JavaScript:

setTimeout(() => {
    document.getElementById("msg").style.display = "none";
}, 3000);

8. Animation-Like Effect

let x = 0;

let move = setInterval(() => {
    x += 10;
    element.style.left = x + "px";

    if (x >= 200) {
        clearInterval(move);
    }
}, 100);

Example Program (Complete)

let count = 10;

let interval = setInterval(() => {
    console.log("Count:", count);
    count--;

    if (count === 0) {
        clearInterval(interval);
        console.log("Finished!");
    }
}, 1000);

Common Mistakes Beginners Make

  • Forgetting to use event.preventDefault() in form-related timers

  • Forgetting to clear intervals

  • Using too many intervals, causing browser slowdown

  • Assuming setTimeout is exact (it can delay slightly)

  • Calling functions instead of passing them (setTimeout(greet(), 1000) is incorrect)

  • Creating unnecessary nested intervals

Practice Tasks (Do It Yourself)

  1. Display "Hello" after 2 seconds.

  2. Create a counter that prints 1 to 10 using setInterval.

  3. Stop the counter when it reaches 10.

  4. Create a message that disappears after 5 seconds.

  5. Build a countdown timer starting from 20.