clearTimeout()

Cancels a pending timeout created by setTimeout() so its callback never runs.

Signature
clearTimeout(timeoutID)
  • Added in JavaScript Baseline widely available since July 2015

Parameters

ParameterTypeDescription
$timeoutIDnumberThe identifier returned by the corresponding setTimeout() call. If it does not identify a pending timer, the call does nothing.

Return value

undefinedNothing.

clearTimeout() cancels a timer scheduled by setTimeout(), provided the callback has not already run. It is deliberately forgiving: an unknown ID, an ID for a timer that already fired, undefined, or the same ID cleared twice are all silent no-ops. Nothing is thrown and nothing is returned, so there is no way to ask whether the cancellation actually caught anything — track that yourself with a flag if it matters.

When to reach for it

Any time a scheduled action can become obsolete before it runs. Debouncing is the canonical case: clear the previous timer on every keystroke and only the last one survives. The same shape covers cancelling a retry when the request finally succeeds, tearing down a component's pending work, and racing a request against a timeout.

What trips people up

You have to keep the ID somewhere both the scheduler and the canceller can see. A const inside a function body is gone by the next call, so debounce state belongs in a closure, a module variable or an instance field — and it should be reset after the callback fires so stale IDs do not linger. Timeout and interval IDs come from one shared pool, so clearTimeout() will happily cancel a setInterval() timer; it works, but pairing the matching functions keeps the intent readable.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Debouncing a search input so only the last keystroke triggers a query
  • Cancelling a scheduled retry once the operation finally succeeds
  • Tearing down pending timers when a view or component is destroyed
  • Aborting a timeout guard after the awaited work completes in time

Frequently asked questions

What happens if I call clearTimeout with an invalid ID?

Nothing at all — the call is a silent no-op that throws no error and returns undefined. The same applies to clearing an ID twice or clearing a timer whose callback has already run, which is why clearTimeout can never tell you whether it actually cancelled anything.

How do I cancel a setTimeout from another function?

Store the ID returned by setTimeout somewhere both functions can reach, such as a closure variable, a module-level binding or an instance property, then pass it to clearTimeout. A local const inside the scheduling function is invisible to the canceller.

Can clearTimeout stop a setInterval?

Yes, because setTimeout and setInterval draw their IDs from one shared pool, so either clear function accepts either kind of ID. It works reliably, but mixing them obscures intent and makes the code harder to audit, so pair clearInterval with setInterval.

More examples

Debounce: only the last call survives

Three calls arrive back to back but only one search executes. Each call cancels the timer the previous one scheduled, so only the final query survives the 30 ms of quiet.

Example · javascript
const results = [];
let timer;

function debouncedSearch(query) {
  clearTimeout(timer);                       // drop the previous plan
  timer = setTimeout(() => results.push(query), 30);
}

debouncedSearch("c");
debouncedSearch("ca");
debouncedSearch("cat");

await new Promise((r) => setTimeout(r, 80));
console.log("queries actually run:", results); // ["cat"]

A cancellable delay

Returning the timer ID alongside the promise makes the delay abortable. The cancelled one is cleared before it fires, so its promise stays pending forever — worth remembering, because awaiting a cancelled delay hangs rather than rejecting.

Example · javascript
function cancellableDelay(ms, label) {
  let id;
  const promise = new Promise((resolve) => {
    id = setTimeout(() => resolve(`${label} completed`), ms);
  });
  return { promise, cancel: () => clearTimeout(id) };
}

const kept = cancellableDelay(20, "kept");
const dropped = cancellableDelay(20, "dropped");
dropped.cancel();

console.log(await kept.promise);
console.log("the cancelled promise never settles");

Clearing a timeout that already fired

Cancelling a timer that has already run is silently ignored rather than reported, so clearTimeout can never tell you whether it caught anything. If you need to know, null out your own handle inside the callback and check that instead.

Example · javascript
const id = setTimeout(() => console.log("callback ran"), 10);

await new Promise((r) => setTimeout(r, 40));

// Too late - the callback is already done.
clearTimeout(id);
console.log("clearTimeout after firing: no error, no effect");

let pending = setTimeout(() => { pending = null; }, 10);
console.log("guard before clearing:", pending !== null);

Discussion

  • Be the first to comment on this lesson.