Skip to main content
JavaScript Basics
CHAPTER 27 Beginner

JavaScript Timers and Intervals

Updated: May 12, 2026
15 min read

# JavaScript Timers and Intervals

Sometimes you don't want your code to run immediately. You might want to wait 3 seconds before showing a popup ad, or you might want to refresh a user's notification feed every 10 seconds.

In this chapter, we will learn how to control time using the browser's built-in Timer functions.

1. Introduction

JavaScript provides two primary methods for executing code at specified time intervals:

  1. 1. setTimeout(): Executes a function exactly once, after a specified delay.
  1. 2. setInterval(): Executes a function repeatedly, waiting a specified delay between each execution.

Both of these functions belong to the global window object, meaning you can call them from anywhere in your code.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Use setTimeout to delay code execution.
  • Pass arguments to timer callbacks.
  • Cancel a delayed execution using clearTimeout.
  • Use setInterval to create loops over time.
  • Stop recurring executions using clearInterval.
  • Build a working Stopwatch / Timer mini-project.

3. setTimeout Syntax

The setTimeout function takes two mandatory parameters:

  1. 1. A callback function (the code to run).
  1. 2. The delay in milliseconds (1000 ms = 1 second).

javascript
1234
// Example JavaScript
setTimeout(() => {
    console.log("This prints after 2 seconds.");
}, 2000);

4. setInterval Syntax

The setInterval function uses the exact same syntax, but it will loop indefinitely until you manually stop it or close the tab.

javascript
1234
// Example JavaScript
setInterval(() => {
    console.log("This prints every 1 second.");
}, 1000);

---

5. Real-world Examples & Code Snippets

Example 1: Showing a Notification Toast

A common use case is displaying a "Saved Successfully!" toast notification, then making it disappear after 3 seconds.

javascript
12345678910
// Example JavaScript
function showToast() {
    const toast = document.getElementById("toast");
    toast.style.display = "block";

    // Hide it after 3000ms
    setTimeout(() => {
        toast.style.display = "none";
    }, 3000);
}

Example 2: Passing Arguments to Timers

If you need to pass data to the callback function, you add them as additional arguments after the delay parameter.

javascript
1234567
// Example JavaScript
function greet(firstName, lastName) {
    console.log(`Hello ${firstName} ${lastName}`);
}

// setTimeout(function, delay, arg1, arg2...)
setTimeout(greet, 1500, "John", "Doe");

Example 3: Canceling a Timeout (clearTimeout)

If the user clicks "Undo", you want to cancel the delete operation before the timeout finishes. setTimeout returns a unique ID number. You pass this ID to clearTimeout().

javascript
12345678910111213
// Example JavaScript
// 1. Start the timer and save its ID
const timerId = setTimeout(() => {
    console.log("File deleted!");
}, 5000);

// 2. User clicked undo before 5 seconds!
function cancelDelete() {
    clearTimeout(timerId);
    console.log("Deletion canceled.");
}

cancelDelete(); // The file will never be deleted.

Example 4: A Digital Clock (setInterval)

We used this in Chapter 14. We want to update the DOM every 1000 milliseconds.

javascript
12345
// Example JavaScript
setInterval(() => {
    const now = new Date();
    document.getElementById("clock").textContent = now.toLocaleTimeString();
}, 1000);

Example 5: Stopping an Interval (clearInterval)

Just like timeouts, intervals return an ID. You must save this ID if you ever want to stop the loop.

javascript
1234567891011121314
// Example JavaScript
let count = 0;

// Save the ID
const intervalId = setInterval(() => {
    count++;
    console.log(`Count is: ${count}`);

    // Stop after 5 times
    if (count === 5) {
        clearInterval(intervalId);
        console.log("Interval stopped!");
    }
}, 1000);

Example 6: The "Zero Delay" Trick

Sometimes you will see setTimeout(func, 0). Why wait 0 seconds? Because JavaScript is single-threaded. By putting a function in a timeout, you push it to the back of the "Event Queue", telling the browser to finish drawing the current HTML screen BEFORE running this heavy function.

javascript
1234567891011
// Example JavaScript
console.log("First");

setTimeout(() => console.log("Second"), 0);

console.log("Third");

// Output Order:
// First
// Third
// Second

Example 7: Using Timers for Animations

Before CSS animations were powerful, developers used setInterval to move elements 1 pixel at a time. While CSS is better now, JS timers are still used for complex canvas game animations.

html
12
<!-- Example HTML -->
<div id="box" style="width:50px; height:50px; background:red; position:absolute;"></div>
javascript
123456789101112
// Example JavaScript
let pos = 0;
const box = document.getElementById("box");

const animId = setInterval(() => {
    if (pos === 200) {
        clearInterval(animId); // Stop moving at 200px
    } else {
        pos++;
        box.style.left = pos + "px"; // Move 1px right
    }
}, 10); // Run every 10 milliseconds

---

6. Common Mistakes for Beginners

  1. 1. Adding () to the callback: setTimeout(myFunc(), 1000) executes myFunc IMMEDIATELY and passes its return value into the timer. You must pass the function reference: setTimeout(myFunc, 1000) or use an arrow function setTimeout(() => myFunc(), 1000).
  1. 2. Losing track of Interval IDs: If you write setInterval(func, 1000) without assigning it to a variable (const id = ...), that loop will run forever, and you have no way to target it to stop it. If you trigger it on a button click, clicking the button 5 times will start 5 concurrent loops!

7. Best Practices

  • Always use Arrow Functions for timer callbacks. As discussed in Chapter 20, arrow functions inherit this from the surrounding scope, which prevents this from breaking inside the timer.
  • Always clear your intervals. If a user navigates to a new "page" in a Single Page App (like React), uncleared intervals will continue running in the background, causing memory leaks and terrible performance.

8. Mini Project: Interactive Stopwatch

Let's build a functional stopwatch with Start, Stop, and Reset buttons using setInterval.

HTML:

html
12345678910111213141516171819202122232425262728
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: monospace; display: flex; justify-content: center; padding-top: 50px; background: #222;}
        .watch { background: #333; padding: 30px; border-radius: 10px; text-align: center; border: 2px solid cyan;}
        .time { font-size: 60px; color: cyan; margin-bottom: 20px;}
        button { background: #007bff; color: white; border: none; padding: 10px 20px; font-size: 18px; cursor: pointer; border-radius: 5px; margin: 0 5px;}
        #btnStop { background: #dc3545; }
        #btnReset { background: #6c757d; }
    </style>
</head>
<body>

    <div class="watch">
        <div class="time" id="display">00:00</div>
        <div>
            <button id="btnStart" onclick="startTimer()">Start</button>
            <button id="btnStop" onclick="stopTimer()">Stop</button>
            <button id="btnReset" onclick="resetTimer()">Reset</button>
        </div>
    </div>

    <script src="stopwatch.js"></script>
</body>
</html>

stopwatch.js:

javascript
12345678910111213141516171819202122232425262728293031323334353637383940
// Example JavaScript
let timerId = null; // Store the interval ID globally
let totalSeconds = 0; // Track the time globally

const display = document.getElementById("display");

function updateDisplay() {
    // Math to get minutes and seconds
    let mins = Math.floor(totalSeconds / 60);
    let secs = totalSeconds % 60;
    
    // Pad with leading zeros (e.g., '05' instead of '5')
    let formattedMins = mins < 10 ? "0" + mins : mins;
    let formattedSecs = secs < 10 ? "0" + secs : secs;
    
    display.textContent = `${formattedMins}:${formattedSecs}`;
}

function startTimer() {
    // Prevent starting multiple intervals if user clicks "Start" 5 times!
    if (timerId !== null) return; 
    
    // Start interval
    timerId = setInterval(() => {
        totalSeconds++;
        updateDisplay();
    }, 1000);
}

function stopTimer() {
    // Clear the interval
    clearInterval(timerId);
    timerId = null; // Reset the ID so we can start again later
}

function resetTimer() {
    stopTimer(); // Stop it first
    totalSeconds = 0; // Reset counter
    updateDisplay(); // Update UI back to 00:00
}

9. Exercises

  1. 1. Write a setTimeout that console logs "Warning: 5 seconds left!" after a 5000ms delay.
  1. 2. Write a setInterval that prints "Tick" every 1000ms. Assign it to a variable named ticker.
  1. 3. Write a single line of code to stop the ticker interval from running.

10. MCQs (Multiple Choice Questions)

Q1: Which function runs code repeatedly at a set interval? A) setTimeout() B) setRecurring() C) setInterval() D) clearTimeout() *Answer: C*

Q2: What argument does clearInterval() require? A) The string name of the function being looped. B) The ID returned by setInterval(). C) The amount of time in milliseconds. D) The document object. *Answer: B*

Q3: Which time unit do JavaScript timers use? A) Seconds B) Microseconds C) Milliseconds D) Nanoseconds *Answer: C*

11. Interview Questions

Q: Are JavaScript timers perfectly accurate? *A: No. Because JavaScript is single-threaded, if a heavy calculation is running on the main thread, the timer callback will be delayed until the main thread is clear. Therefore, setTimeout(func, 1000) means "run this in AT LEAST 1000ms", not exactly 1000ms.*

12. FAQs

Q: What if I need an interval faster than 1 millisecond? *A: Browsers intentionally cap the minimum delay of setInterval and setTimeout (usually at 4ms). If you are building high-performance animations or games, you should use requestAnimationFrame() instead.*

13. Summary

  • setTimeout(func, delay) runs code ONCE after a delay.
  • setInterval(func, delay) runs code REPEATEDLY every delay.
  • Time is always in milliseconds (1000ms = 1s).
  • Use clearTimeout(id) and clearInterval(id) to stop them.
  • Always store the returned ID in a variable if you need to stop the timer.

14. Next Chapter Recommendation

Timers and Fetch both execute code *asynchronously* (in the background, outside the main flow of execution). Managing asynchronous code using nested callbacks can become incredibly messy. In the next chapter, JavaScript Async Programming, we will master Promises and the modern async/await syntax.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·