Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
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.

cancelTimout();

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

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?