Using `setTimeout` & `setInterval`: JS Timers

Master asynchronous JavaScript by learning how to delay tasks and create repeating actions with these essential timing functions.

Lesson ProgressStep 1 of 7
...
0 EXP

Welcome! Let's explore JavaScript's timers: `setTimeout` for delays and `setInterval` for repetitions.

// Mastering Time in JS...

`setTimeout`: The One-Time Delay

The `setTimeout` function is a Web API that schedules a "callback" function to be executed **once** after a specified delay in milliseconds.

// setTimeout(callback, delayInMs)

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

It returns a numerical **Timer ID**, which you can save in a variable. This ID is used to cancel the timer before it executes.

You can also pass additional arguments to `setTimeout` that will be passed directly to your callback function when it's called:

function greet(name) {
  console.log(`Hello, ${name}!`);
}

setTimeout(greet, 1000, "Maria");
// Output after 1 sec: "Hello, Maria!"

System Check

You want to run a function `showAd()` exactly once, 5 seconds after the page loads. What is the correct syntax?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

🏆
Time Lord

Successfully use setTimeout and setInterval in an exercise.

🚫
Loop Breaker

Correctly use clearTimeout and clearInterval to stop timers.

🔄
Async Acolyte

Demonstrate understanding of the JavaScript Event Loop.

Mission: Build a Timer System

Write JavaScript to:
1. Log "Hello" after 1 second using `setTimeout`.
2. Log "Tick" every 2 seconds using `setInterval`.
3. Stop the "Tick" log after 5 seconds using `clearTimeout` (inside a `setTimeout`).

A.D.A. Feedback:

> Awaiting input...

Challenge: Order the Event Loop

When you call `setTimeout`, what is the correct order of operations? Drag the steps into the correct logical order.

Timer Finishes (Web API)
Event Loop moves task to Call Stack
setTimeout() is called (Call Stack)
Callback is added to Callback Queue

Challenge: Complete the Syntax

Fill in the missing parts to create an interval that runs every second and is then stopped.

const = (() => {...}, 1000);
();

Consult A.D.A.

Community Holo-Net

Peer Project Review

Submit your "Timer System" project for feedback from other Net-Runners.

Mastering Time: A Deep Dive into JavaScript Timers

JavaScript, at its core, is a single-threaded language. This means it can only execute one command at a time. This would be a huge problem if a long-running task (like fetching data or waiting for a timer) blocked all other code. Imagine clicking a button and having the entire webpage freeze for 5 seconds!

This is where asynchronous programming comes in. Timer functions like `setTimeout` and `setInterval` are not part of JavaScript itself; they are part of the **Web API** (provided by the browser). They allow you to schedule code to run later, handing off the "waiting" part to the browser. This frees up the JavaScript thread to continue with other tasks, keeping your site responsive.

`setTimeout`: The One-Time Delay

The `setTimeout` function schedules a function (a "callback") to run **once** after a specified delay in milliseconds.

// Syntax: setTimeout(callback, delayInMs, param1, param2, ...)

// Example: Show a message after 2 seconds
const timerId = setTimeout(() => {
  console.log("This message appears after 2 seconds!");
}, 2000);

// You can also pass arguments to the callback
setTimeout((name) => {
  console.log(`Hello, ${name}!`);
}, 1000, "Alice");

It returns a unique `timerId`, which is just a number. You can use this ID to cancel the timer before it runs using `clearTimeout(timerId)`.

The "Zero Delay" Myth: `setTimeout(fn, 0)`

You might see code like `setTimeout(myFunction, 0)`. This does **not** run the function immediately. Instead, it places `myFunction` in the Callback Queue to be executed as soon as the Call Stack is empty. This is a useful trick to "defer" a task until after the current synchronous code has finished running, preventing it from blocking the main thread.

`setInterval`: The Repeating Task

The `setInterval` function is similar, but it **repeatedly** executes a callback function at a fixed time interval.

// Syntax: setInterval(callback, delayInMs, param1, ...)

// Example: Log "Tick" every 1 second
let count = 0;
const intervalId = setInterval(() => {
  count++;
  console.log(`Tick ${count}`);

  if (count >= 5) {
    clearInterval(intervalId); // CRITICAL: Always stop intervals!
    console.log("Stopped!");
  }
}, 1000);

Like `setTimeout`, it returns an `intervalId` which you **must** use with `clearInterval(intervalId)` to stop the repetition. Forgetting to do this will create a memory leak and your function will run forever.

The Pitfall of `setInterval`

`setInterval` can be problematic. It schedules a new execution every `delayInMs` **regardless** of whether the previous execution has finished. If your callback function takes 300ms to run and your interval is 200ms, your tasks will start to stack up, causing performance issues.

A more robust pattern is to use a **recursive `setTimeout`**, which only schedules the next call *after* the current one has finished.

// Robust alternative to setInterval
const runRepeatedly = () => {
  console.log("Running task...");

  // ...do complex work here...

  setTimeout(runRepeatedly, 1000); // Schedule the *next* run
};

setTimeout(runRepeatedly, 1000); // Start the loop

Understanding the Event Loop

How does this all work? JavaScript's concurrency model is based on an **Event Loop**. Here's a simplified breakdown:

  • Call Stack: Where your synchronous code is executed, one line at a time.
  • Web APIs: Where the browser handles asynchronous tasks. When you call `setTimeout`, the timer is handed off to the Web API, and the Call Stack becomes free.
  • Callback Queue (or Message Queue): When the timer (in the Web API) finishes, its callback function is moved to the Callback Queue.
  • Event Loop: This is a simple process that constantly checks: "Is the Call Stack empty?" If it is, it takes the first task from the Callback Queue and pushes it onto the Call Stack to be executed.

This is why `setTimeout(fn, 0)` doesn't run immediately: it goes `Call Stack` -> `Web API` -> `Callback Queue`, and only runs when the `Call Stack` is completely empty.

Advanced Patterns: Debouncing & Throttling

Timers are the building blocks for two essential performance patterns:

✔️ Debouncing

**Analogy:** Waiting for someone to finish talking before you reply.
**Use Case:** A search bar. You don't want to search on every keystroke. You wait until the user has *stopped* typing for 300ms, then send the request. This is done by `clearTimeout` on every keypress and setting a new `setTimeout`.

✔️ Throttling

**Analogy:** Only allowing one person through a turnstile every 1 second, even if a crowd is pushing.
**Use Case:** A "scroll" event listener. A scroll event can fire hundreds of times. Throttling ensures your function (e.g., checking if an element is in view) only runs, at most, once every 100ms.

Key Takeaway: Timers are your tool for managing the fourth dimension in JavaScript. Use `setTimeout` for one-time events, prefer a recursive `setTimeout` over `setInterval` for robust loops, and always `clear` your timers to prevent leaks.

JavaScript Timers & Async Glossary

Asynchronous
Code that runs in the background, outside the main flow of execution, allowing the rest of the program to continue. Timers and data fetching are common examples.
Callback Function
A function passed as an argument to another function, which is then executed at a later time (e.g., after a timer finishes).
Call Stack
A data structure that records where in the program we are. Synchronous function calls are "pushed" onto the stack and "popped" off when they return.
Callback Queue (Message Queue)
A waiting area for callback functions that are ready to run. Tasks from Web APIs (like timers) are placed here when they complete.
clearInterval(timerId)
Stops the repeated execution of a timer created by `setInterval`.
clearTimeout(timerId)
Cancels a delayed function call created by `setTimeout` before it has a chance to run.
Debouncing
A performance pattern that delays executing a function until a certain amount of time has passed since the last time it was invoked. (e.g., search bar).
Event Loop
The core of JavaScript's concurrency model. A process that continuously checks if the Call Stack is empty and, if so, moves a task from the Callback Queue to the Call Stack.
Recursive setTimeout
A pattern of creating a repeating loop where a function calls `setTimeout` on itself. It's often preferred over `setInterval` as it waits for the previous execution to complete.
setInterval(callback, delay)
A Web API function that repeatedly executes a callback function at a specified millisecond interval.
setTimeout(callback, delay)
A Web API function that executes a callback function **once** after a specified millisecond delay.
Single-Threaded
A programming language model where code is executed one command at a time, in sequence. JavaScript is single-threaded.
Throttling
A performance pattern that ensures a function is only executed, at most, once per specified time period (e.g., once every 100ms).
Web API
A set of features provided by the browser (not the JavaScript engine) that handle asynchronous tasks, such as timers (`setTimeout`), DOM events, and data fetching (`fetch`).

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of web development experts, who have years of experience teaching JavaScript and building robust, asynchronous web applications.

Verification and Updates

Last reviewed: October 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on the latest ECMAScript specifications and browser APIs.

External Resources

Found an error or have a suggestion? Contact us!