How do you add a time delay before executing code using setTimeout in JavaScript? | A1Lab@FahadM to JavaScriptEnglish •
edit-2
3 days ago

How do you add a time delay before executing code using setTimeout in JavaScript?

message-square
0

To add a time delay before executing code in JavaScript, pass a callback function and a delay in milliseconds to setTimeout(callback, delayMs, ...args). Keep in mind that delayMs specifies the minimum delay before the callback is queued onto the event loop (not a guaranteed exact execution timestamp), and always save the returned timer ID if you may need to cancel a pending timer with clearTimeout(timerId).


1. Scheduling a Delayed Callback with setTimeout() and clearTimeout()

Pass your function, the delay in milliseconds (for example, 1500 for 1.5 seconds), and any optional arguments to setTimeout(); store the numeric/handle ID returned by setTimeout() so you can cancel it cleanly if the user navigates away or triggers a newer action:

// Schedule a delayed callback and return a controller to cancel it if needed
function scheduleDelayedAction(action, delayMs = 1000, ...args) {
  if (typeof action !== "function") {
    throw new TypeError("Expected action to be a function.");
  }

  if (typeof delayMs !== "number" || !Number.isFinite(delayMs) || delayMs < 0) {
    throw new RangeError("Expected delayMs to be a non-negative finite number.");
  }

  const timerId = setTimeout(() => {
    action(...args);
  }, delayMs);

  return {
    timerId,
    cancel() {
      clearTimeout(timerId);
    }
  };
}

// Example usage:
const job = scheduleDelayedAction((label) => {
  console.log("Executed:", label);
}, 500, "Save draft");

// To cancel before 500 ms elapses:
// job.cancel();
  • Minimum delay, not exact timing: If synchronous code or heavy rendering blocks the main thread past delayMs, the callback waits until the call stack clears.
  • Avoid string callbacks: Always pass a function reference or arrow function rather than a string (setTimeout("code()", 100)), which acts like eval() and causes CSP/security and scoping issues.

2. Wrapping setTimeout in a Promise for async/await

When you want a clean pause inside an async function—such as retrying a request or pacing UI transitions—wrap setTimeout inside a Promise (and support AbortSignal so callers can cancel the delay cleanly):

// Async sleep helper with optional AbortSignal cancellation support
function delay(ms, signal) {
  if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) {
    throw new RangeError("Expected ms to be a non-negative finite number.");
  }

  if (signal?.aborted) {
    return Promise.reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
  }

  return new Promise((resolve, reject) => {
    const onAbort = () => {
      clearTimeout(timerId);
      reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
    };

    const timerId = setTimeout(() => {
      signal?.removeEventListener("abort", onAbort);
      resolve();
    }, ms);

    signal?.addEventListener("abort", onAbort, { once: true });
  });
}

// Example usage inside an async workflow:
async function runWithPause() {
  console.log("Starting...");
  await delay(300);
  console.log("Resumed after ~300 ms");
}

runWithPause();
  • Clean sequential pacing: Awaiting delay(ms) avoids deeply nested callbacks while keeping execution non-blocking.
  • Prevent leaked timers: Clearing timerId on abort ensures aborted delays do not fire later in the background.

TL;DR: Call setTimeout(fn, delayMs) (with delay in milliseconds) to schedule code after a minimum wait, use clearTimeout(timerId) to cancel pending timers, or wrap setTimeout in a Promise when using async/await.