Delayed Execution

JavaScript can schedule code to run in the future instead of immediately.

1. setTimeout — Run Once After a Delay

function greetUser() {
  alert('Hello after 2 seconds!');
}

let timerId = setTimeout(greetUser, 2000); // 2000ms = 2 seconds

To cancel a timer before it fires:

clearTimeout(timerId);

2. setInterval — Run Repeatedly

// Alerts "Tick!" every 2 seconds
let timerId = setInterval(() => alert('Tick!'), 2000);

// Stop it after 5 seconds
setTimeout(() => clearInterval(timerId), 5000);

Nested setTimeout — A Better Alternative

Using nested setTimeout instead of setInterval gives you more control, because it guarantees a fixed gap between executions (not just between start times):

let delay = 1000;
setTimeout(function request() {
  // ... make a request ...
  delay *= 2; // Increase delay on each iteration
  setTimeout(request, delay);
}, delay);
Caution

Timers don't guarantee millisecond precision. If the CPU is heavily loaded, execution may be delayed. setTimeout(f, 0) doesn't mean " run instantly " — it means " run as soon as possible after the current task. "

Tip

setTimeout(f, 0) is a classic trick to defer code execution until after the current call stack has cleared, which is useful for releasing the browser to re-render before starting heavy work.