Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

A better setTimeout() in JavaScript

A pretty long ago, I covered how to handle multiple time intervals in JavaScript in this article. And that’s a good way to handle multiple intervals in JavaScript. In line with that, I recently stumbled upon a pretty interesting way to handle setTimeout() in JavaScript in this tweet by Haz.

Essentially, when you define a setTimeout(), it returns a number which is the ID of the timer. You can use this ID to clear the timer using the clearTimeout() function. The function Haz describes cleverly uses this ID to create a better setTimeout() function.

function onTimeout(timeout: number, handler: () => void) {
  const timeoutId = setTimeout(handler, timeout);
  return () => clearTimeout(timeoutId);

As you can tell, the function above takes two arguments. The first one is the timeout in milliseconds and the second one is the handler function which will be called after the timeout.

The function returns a function that when called, clears the timer. So, essentially, you can use this function to create a better setTimeout() function like so.

const cancelTimout = onTimeout(1000, () => {
  console.log("Hello after 1 second");

And if you want to clear the timer for some reason (before it times out), you can call the function returned by the onTimeout() function like so.


Pretty neat, isn’t it? This is a great way to handle setTimeout() in JavaScript.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I do and want me to continue doing the same, I'd like you consider leaving a tip. I'd highly appreciate that. Cheers!