Cancellable Timeout

Nritam KumarNritam Kumar
1 min read

setTimeout and clearTimeout are two essential functions in JavaScript used for managing timed events.

setTimeout

setTimeout is used to execute a function or a piece of code after a specified delay (in milliseconds). It returns a unique identifier (timeoutID) that can be used to cancel the timeout if needed.

clearTimeout

clearTimeout is used to cancel a timeout that was previously established by calling setTimeout.

Example:

let timeoutID = setTimeout(() => {
  console.log('This message will not be displayed');
}, 2000);

clearTimeout(timeoutID); // Cancels the timeout

Our goal is to Implement a function setCancellableTimeout, that acts like setTimeout but instead of returning a timer ID, it returns a function that when called, cancels the pending callback function

let i = 0;
// t = 0:
const cancel = setCancellableTimeout(() => {
  i++;
}, 100);
// t = 50:
cancel();
// t = 100: i is still 0 because cancel() was called.

Solution :
The return value of a setTimeout function is timeoutID which can be used to clearTimeout. So we will return a function which when called will cancel the setTimeout

export default function setCancellableTimeout(
  callback: Function,
  delay?: number,
  ...args: Array<any>
): () => void {
  const timer=setTimeout(callback,delay,...args);
  return ()=>clearTimeout(timer);
}
0
Subscribe to my newsletter

Read articles from Nritam Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nritam Kumar
Nritam Kumar