JavaScript Window setTimeout() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
One-shot delay

What You’ll Learn

The setTimeout() method runs a function once after a delay. This tutorial covers syntax, timeout IDs, asynchronous execution order, passing arguments, canceling with clearTimeout(), comparison with setInterval(), five examples, and common patterns like toasts and debouncing.

01

Syntax

setTimeout(fn, ms)

02

Once

Single run

03

ID

Save return value

04

Cancel

clearTimeout(id)

05

Async

Non-blocking

06

Args

Extra parameters

Introduction

Not everything should happen instantly. Toast notifications disappear after a few seconds, search boxes wait until the user stops typing, and welcome messages appear after a short pause. The setTimeout() method schedules a callback to run once after a delay in milliseconds.

Timers are asynchronous: JavaScript keeps running while the clock counts down. That keeps pages responsive. Store the returned timeout ID if you might need to cancel the scheduled work with clearTimeout() before it fires.

Understanding the setTimeout() Method

setTimeout(callback, delayMs, arg1, arg2, ...) registers callback to run one time after at least delayMs milliseconds. It returns a numeric ID immediately; the callback is not invoked synchronously.

Minimum delays are clamped in browsers (often ~4ms). Background tabs may throttle timers heavily. For repeating work, use setInterval() or chain recursive setTimeout() calls when you need pauses between runs.

💡
Beginner Tip

Always pass a function—not a string: setTimeout(() => console.log("Hi"), 1000). String arguments behave like eval() and are discouraged.

📝 Syntax

General form of setTimeout():

JavaScript
const timeoutId = setTimeout(callback, delayMs, param1, param2);

// shorthand (same in browsers):
const id = setTimeout(greet, 2000);

Parameters

  • callback — function executed once after the delay.
  • delayMs — milliseconds to wait. Use 1000 for one second.
  • param1, param2, ... (optional) — values passed to callback.

Return value

  • A numeric timeout ID. Pass it to clearTimeout() to cancel.

Related APIs

  • clearTimeout(id) — cancel a pending timeout.
  • setInterval(fn, ms) — repeat on a timer.
  • clearInterval(id) — stop a repeating timer.
  • queueMicrotask(fn) — run before the next timer (microtask queue).

⚡ Quick Reference

TopicDetail
Delay oncesetTimeout(fn, ms)
After 2 secondssetTimeout(fn, 2000)
Cancel pendingclearTimeout(id)
Pass argumentssetTimeout(fn, 1000, "Hi")
Repeat foreversetInterval(fn, ms) instead
Run now, delay workCode after setTimeout runs first

📋 setTimeout() vs setInterval() vs clearTimeout()

Schedule one delayed run, repeat on a timer, or cancel before it fires.

setTimeout
setTimeout(fn, 2000)

Runs once after 2s

setInterval
setInterval(fn, 2000)

Repeats every 2s

clearTimeout
clearTimeout(id)

Cancel pending run

Recursive
fn + setTimeout(fn)

Repeat with gaps

Examples Gallery

Use the Try-it links to schedule delayed callbacks in the browser. Watch execution order and learn when to cancel timers.

📚 Getting Started

Greet the user after a two-second pause.

Example 1 — Basic Delayed Callback

Run a function once after 2000 milliseconds.

JavaScript
function greet() {
  console.log("Hello, world!");
}

setTimeout(greet, 2000);
Try It Yourself

How It Works

The timer starts immediately; greet runs once when the delay elapses. Nothing repeats unless you call setTimeout again.

📈 Practical Patterns

Async order, cancellation, arguments, and UI feedback.

Example 2 — Asynchronous Execution Order

Code after setTimeout runs before the delayed callback.

JavaScript
console.log("This runs immediately.");

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

console.log("This also runs immediately.");
Try It Yourself

How It Works

setTimeout schedules work on the timer queue. Synchronous lines finish first—this is why beginners sometimes expect the delayed log to appear instantly.

Example 3 — Cancel with clearTimeout()

Prevent the callback if the user acts before the delay ends.

JavaScript
const timerId = setTimeout(function () {
  console.log("This will run unless cleared.");
}, 3000);

clearTimeout(timerId);
console.log("Timeout cancelled.");
Try It Yourself

How It Works

Call clearTimeout only before the callback runs. After it fires, clearing the same ID does nothing harmful. See the clearTimeout() tutorial for debounce patterns.

Example 4 — Pass Arguments to the Callback

Forward values without wrapping in another function.

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

setTimeout(greet, 1500, "World");
Try It Yourself

How It Works

Arguments after the delay are passed to greet when the timer fires—equivalent to setTimeout(() => greet("World"), 1500).

Example 5 — Auto-Hide a Toast Message

Show feedback, then remove it after three seconds.

JavaScript
function showToast(message) {
  const el = document.getElementById("toast");
  el.textContent = message;
  el.hidden = false;

  setTimeout(function () {
    el.hidden = true;
  }, 3000);
}

showToast("Saved successfully!");
Try It Yourself

How It Works

One-shot delays fit temporary UI. Store the timeout ID if a new toast should cancel the previous hide timer.

🚀 Common Use Cases

  • Delayed messages — show content after a welcome pause.
  • Toasts and alerts — auto-dismiss after a few seconds.
  • Debounced search — wait until typing stops (with clearTimeout).
  • Animation steps — chain short delays between CSS changes.
  • Retry logic — attempt an API call again after backoff.
  • Focus management — move focus after a modal opens.

🧠 What Happens When You Call setTimeout()

1

Register timer

Browser stores callback + delay; returns timeout ID immediately.

Start
2

Script continues

Synchronous code after setTimeout runs without waiting.

Async
3

Delay elapses

After ~delayMs, callback enters the task queue (unless cleared).

Wait
4

Callback runs once

Function executes a single time; ID becomes inactive.

📝 Notes

  • Never pass a string as the callback—use functions only.
  • setTimeout(fn, 0) does not run instantly; it queues after current synchronous code.
  • Recursive setTimeout can replace setInterval when delays must vary.
  • Background tabs throttle timers; do not rely on sub-second precision there.
  • For repeating logs every second, prefer setInterval over recursive timeout unless you need dynamic spacing.
  • Modern apps often use async/await with Promises, but setTimeout remains the underlying browser primitive.

Browser Support

setTimeout() has been supported since the earliest JavaScript timer APIs in browsers and matches universal runtime support.

Universal · Standard API

setTimeout()

Supported in Chrome, Firefox, Safari, Edge, Opera, Node.js, and WebViews. Works alongside clearTimeout() everywhere timers exist.

100% Universal support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
setTimeout() Universal

Bottom line: Safe to use in any JavaScript environment with timers. Store IDs when you need clearTimeout()—not polyfills.

Conclusion

setTimeout() schedules a function to run once after a delay and returns an ID for optional cancellation. It is the building block for delayed UI, debouncing, and asynchronous flow in beginner JavaScript.

Pair it with clearTimeout(), compare with setInterval() for repeating tasks, and always pass function references—not strings—to your timers.

💡 Best Practices

✅ Do

  • Save the timeout ID when cancellation is possible
  • Pass function references or arrow functions
  • Use clearTimeout in debounce patterns
  • Pick realistic delays (300–500ms for debounce, 3000ms for toasts)
  • Explain async order to users when UI updates feel “late”

❌ Don’t

  • Pass strings as the first argument
  • Assume callbacks run before the next line of code
  • Stack many timeouts without clearing old ones in debounce
  • Use setTimeout for tight animation loops—try rAF
  • Confuse one-shot timeouts with setInterval loops

Key Takeaways

Knowledge Unlocked

Five things to remember about setTimeout()

Your foundation for one-shot delayed execution in JavaScript.

5
Core concepts
02

Once

Single run.

Delay
🔖 03

ID

Store return.

Handle
🛑 04

Cancel

clearTimeout.

Cleanup
🔄 05

Async

Non-blocking.

Order

❓ Frequently Asked Questions

It schedules a function to run once after a delay in milliseconds. The browser returns a numeric timeout ID immediately; the callback runs later on the event loop—not right away.
A numeric timeout ID. Store it—e.g. const id = setTimeout(fn, 2000)—so you can cancel with clearTimeout(id) before the callback runs.
setTimeout(fn, ms) runs the callback one time after the delay. setInterval(fn, ms) repeats until clearInterval(). Use setTimeout for delays, toasts, and debouncing; setInterval for clocks and polling.
No. setTimeout is asynchronous. Lines after the call run immediately while the timer counts down in the background.
Yes. Extra arguments after the delay are forwarded: setTimeout(greet, 2000, "Alex"). Or use an arrow function: setTimeout(() => greet("Alex"), 2000).
No. Legacy browsers allowed setTimeout("alert('hi')", 1000) which behaves like eval. Always pass a function reference or arrow function for security and readability.
Did you know?

A classic debounce pattern clears the previous timeout on every keystroke and starts a fresh setTimeout—so the search runs only after the user pauses typing. That is one of the most common production uses of setTimeout paired with clearTimeout.

Continue to stop()

Learn how to stop a loading document with the window.stop() method.

stop() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful