DEV Community

Blake Lamb
Blake Lamb

Posted on

4 2

Using clearTimeout in JavaScript

Overview & Setup

This article will show how to use the clearTimeout function in JavaScript. This function allows you to use cancel a setTimeout before it resolves.In this example I will use an angular project in StackBlitz, but as this is a JavaScript feature, it can be used in any JavaScript environment.

To see a working use of this, you can checkout my example project here .

Getting Into It

There are many possible use cases in which using clearTimeout may be advantageous. For example, if you want to have an input field fire off a search when the user types in it, but you want to wait until the user stops typing to run the search function. You would need to use setTimeout in this situation to delay the search function. But without a way to cancel that timeout, the function would still run on every key stroke.

So to get the desired behavior and cancel the timeout, you would need to implement something like this:

  setTO = () => {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
    this.timeoutId = setTimeout(() => {
      this.running = false;
      this.completed = true;
    }, 3000);
  };
Enter fullscreen mode Exit fullscreen mode

In this function, we look to see if there is already a timeout. If there is, we clear it and set a new one. So in this example the user would need to not input anything for 3 seconds before the timeout resolves.

Conclusion

That is the basic implementation and situation of when you might need or want to use clearTimeout. It is a function that has helped me in my coding and hopefully this can help you too! Again, to see my Stackblitz example with a working implementation, click here.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay