LOGBOOK

HELP

Quiz Entry - updated: 2026.07.05

How do you run code after a delay in JavaScript?

Call setTimeout(callback, ms) to run code once after a delay (use setInterval to repeat), and cancel with clearTimeout/clearInterval.

// Run after 2 seconds (2000ms)
setTimeout(() => {
    console.log("Delayed message");
}, 2000);

// With named function
function showAlert() {
    alert("Time's up!");
}
setTimeout(showAlert, 5000);

Canceling a timeout:

const timeoutId = setTimeout(doSomething, 3000);
// Cancel before it runs
clearTimeout(timeoutId);

For repeated execution, use setInterval:

const intervalId = setInterval(() => {
    console.log("Every second");
}, 1000);

// Stop repeating
clearInterval(intervalId);

Common use cases:

  • Debouncing user input
  • Auto-hiding notifications
  • Animation delays
  • Polling (with setInterval)

Go deeper:

  • doc setTimeout (MDN) — return value, clearTimeout, throttling in background tabs, and passing arguments.

From Quiz: WEBT / Frontend | Updated: Jul 05, 2026