Hi there, I'm Marcos!

⏱ Cancelling setTimeout and setInterval executions

// setTimeout
const timeoutId = setTimeout(() => {
  console.log('This will be executed once after 1000ms');
}, 1000);

clearTimeout(timeoutId);

// setInterval
const intervalId = setInterval(() => {
  console.log('This will be executed repeatedly after 1000ms');
}, 1000);

clearInterval(intervalId);

Ever wondered how to cancel the execution of a timeout or an interval in JavaScript? You might have faced the case where you don't need the executions of any of these functions anymore. Both setTimeout and setInterval return an id that you can use it later as parameter for clearTimeout and clearInterval functions respectively. This will stop further executions once and for all.

Fun fact: according to the documentation, you can use the clearTimeout and clearInterval interchangeably as the ids come from a shared pool. This is discouraged though for readability purposes.