setTimeout() schedules a function to run once after at least the specified delay. It is useful for reminders, delayed UI actions, debouncing, and scheduling the next step of recurring work.
setTimeout(() => {
console.log("Runs once after about 2 seconds");
}, 2000);
const timeoutId = setTimeout(callback, delay);
The delay is in milliseconds and the return value is a timeout ID that can be passed to clearTimeout().
function showReminder() {
console.log("Take a break");
}
setTimeout(showReminder, 5000);
Avoid older string forms such as setTimeout('showReminder()', 5000).
const id = setTimeout(showReminder, 5000);
clearTimeout(id);
function notify(message) {
console.log(message);
}
setTimeout(notify, 1000, "Done");
The callback becomes eligible to run after the delay. A busy main thread, browser scheduling, or background-tab throttling can make it run later. For a deadline, compare the current time with the target time instead of counting timeout calls.
A zero delay does not run the callback immediately or before the current JavaScript finishes. It schedules the callback for a later task when the event loop is able to run it.
console.log("A");
setTimeout(() => console.log("C"), 0);
console.log("B");
// A, B, then C
function repeat() {
doWork();
setTimeout(repeat, 1000);
}
See recursive setTimeout(). For fixed repeating callbacks, see setInterval().
const seconds = Number(delayInput.value);
if (Number.isFinite(seconds) && seconds >= 0) {
setTimeout(() => alert("Reminder"), seconds * 1000);
}
If the reminder must survive a reload or browser restart, save an absolute target timestamp and recompute the remaining time after loading; a plain in-memory timeout is not persistent.
Related: periodic click example, window alert, stopwatch.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.