JavaScript setTimeout() Timer

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);

setTimeout() Syntax and Return Value Top ↑

const timeoutId = setTimeout(callback, delay);

The delay is in milliseconds and the return value is a timeout ID that can be passed to clearTimeout().

Pass a Function Instead of a String Top ↑

function showReminder() {
  console.log("Take a break");
}
setTimeout(showReminder, 5000);

Avoid older string forms such as setTimeout('showReminder()', 5000).

Cancel a Pending Timeout Top ↑

const id = setTimeout(showReminder, 5000);
clearTimeout(id);

Pass Arguments to the Callback Top ↑

function notify(message) {
  console.log(message);
}
setTimeout(notify, 1000, "Done");

The Delay Is a Minimum, Not an Exact Appointment Top ↑

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.

What Does setTimeout(..., 0) Mean? Top ↑

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

Use setTimeout() Recursively for Controlled Repetition Top ↑

function repeat() {
  doWork();
  setTimeout(repeat, 1000);
}

See recursive setTimeout(). For fixed repeating callbacks, see setInterval().

Simple Reminder with User-Selected Delay Top ↑

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.

Common setTimeout() Mistakes Top ↑

  • Passing the result of a function call instead of the function itself.
  • Using strings as code.
  • Assuming millisecond-perfect execution.
  • Forgetting to cancel timers when a UI action is abandoned.
  • Using a timeout as durable scheduling for tasks that must survive navigation or shutdown.

Related: periodic click example, window alert, stopwatch.




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer