Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

clearTimeout

Cancels a scheduled setTimeout.

Available since: Web API

Syntax

clearTimeout(timeoutId)

Parameters

ParameterTypeDescription
timeoutIdnumberThe id returned by setTimeout.

Return value

undefinedReturns nothing.

Examples

A timer cancelled before it fires:

const id = setTimeout(() => console.log('never printed'), 500);
 
clearTimeout(id);
console.log('cancelled');

Output:

cancelled

Debounce — act only after a pause in input:

function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}
 
const search = debounce((text) => console.log('search:', text), 100);
search('a');
search('an');
search('ann');

Output:

search: ann

Notes

Cancelling a timer that already fired or does not exist does nothing and throws no error.

See also

Related recipes

In the tutorial

  • Timers — The setTimeout and setInterval functions in JavaScript: delayed and repeated calls, arguments, cancelling a timer.

Thanks for reading!

Donate to the site — we work hard for you.