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 Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: