Clear all the timeout objects from webpage in Javascript

setTimeout function is used to achieve asynchronous tasks in JavaScript.

The return value of setTimeout is an Integer. This value can be passed to clearTimeout method to clear that timeout.

Ex: const x = setTimeout(() => {}, 1000); // x will be any number ex: 1

clearTimeout(x) // this will clear the timeout created above.

To clear all the timeouts object in a webpage window, first they must be captured.

Consider you’ve some timeouts are initiated from page one, and the user navigated to page two, the timeouts from page will still preserve space in memory, and they might get executed after the navigation to the second page, which might lead to inconsistent behaviors or bugs. In order to clear all the timeouts on certain conditions

There are a few ways to accomplish that, we are going to explore two of them.


Option1: Using array to store the timeouts, then looping over to clear them

The way we can accomplish this, is by simply creating some timeout instances, and store the instance into javascript array, as shown below:

const timeouts = [];

const timeout1 = setTimeout(function() {
    console.log(1);
}, 200);

const timeout2 = setTimeout(function() {
    console.log(2);
}, 300);

const timeout3 = setTimeout(function() {
    console.log(3);
}, 400);

// Storing the timeouts instances into JS array
timeouts.push(timeout1);
timeouts.push(timeout2);
timeouts.push(timeout3);

Then, whenever we want to clear all the timeouts at later time, or once any action is met, simply we can pass over the array and clear them one by one, as the following:

const timeouts = [];

const timeout1 = setTimeout(function() {
    console.log(1);
}, 200);

const timeout2 = setTimeout(function() {
    console.log(2);
}, 300);

const timeout3 = setTimeout(function() {
    console.log(3);
}, 400);

timeouts.push(timeout1);
timeouts.push(timeout2);
timeouts.push(timeout3);

setTimeout(() => {
    for (var i = 0; i < timeouts.length; i++) {
        clearTimeout(timeouts[i]);
    }

    console.log('All timeouts Cleared!')
}, 1000)

Note: I have wrapped the clear timeout process into another setTimeout just to simulate the process of clearing them at a later time while running the application.


Option2: Using a global utility object to hold all the timeouts instances

export const TIMEOUTS = {
    timeouts: [],
    setTimeout: function(fn, delay) {
        const id = setTimeout(fn, delay);
        this.timeouts.push(id);
    },
    clearAllTimeouts: function() {
        while (this.timeouts.length) {
            clearTimeout(this.timeouts.pop())
        }
    }
}

TIMEOUTS.setTimeout(() => console.log('First timer'), 1000)
TIMEOUTS.setTimeout(() => console.log('Second timer'), 1000)

setTimeout(() => {
    TIMEOUTS.clearAllTimeouts();
    console.log('All timeouts Cleared!');
}, 1000)

In this way, you can call the TIMEOUTS at any file, and add/clear all the timeouts when needed.

When you’re living the page, you can call TIMEOUTS.clearAllTimeouts();  which will clear all the timeouts that are created so far.


Photo from Unsplash.

Related Posts

How to remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: