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
Fundamentals
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.
Concept
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.
Foundation
📝 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).
Cheat Sheet
⚡ Quick Reference
Topic
Detail
Delay once
setTimeout(fn, ms)
After 2 seconds
setTimeout(fn, 2000)
Cancel pending
clearTimeout(id)
Pass arguments
setTimeout(fn, 1000, "Hi")
Repeat forever
setInterval(fn, ms) instead
Run now, delay work
Code after setTimeout runs first
Compare
📋 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
Hands-On
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);
This runs immediately.
This also runs immediately.
(after 2s)
This runs after 2 seconds.
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.");
Timeout cancelled.
( delayed message never appears )
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");
One-shot delays fit temporary UI. Store the timeout ID if a new toast should cancel the previous hide timer.
Applications
🚀 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.
Important
📝 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.
Compatibility
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 ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll 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.
Wrap Up
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.
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
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about setTimeout()
Your foundation for one-shot delayed execution in JavaScript.
5
Core concepts
📝01
Syntax
setTimeout(fn, ms)
API
⏳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.