"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can You Control and Track Timeouts in JavaScript?

How Can You Control and Track Timeouts in JavaScript?

Published on 2024-11-08
Browse:530

How Can You Control and Track Timeouts in JavaScript?

Pausing and Resuming Timeouts in JavaScript

How to pause and resume a setTimeout() timeout?

You can wrap the window.setTimeout function to create a custom timer that supports pausing and resuming.

var Timer = function(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        timerId = null;
        remaining -= Date.now() - start;
    };

    this.resume = function() {
        if (timerId) {
            return;
        }

        start = Date.now();
        timerId = window.setTimeout(callback, remaining);
    };

    this.resume();
};

How to get the time remaining on the current timeout?

You can use the remaining property of the custom timer to get the time remaining on the current timeout.

var timer = new Timer(function() {
    alert("Done!");
}, 1000);

console.log("Time remaining:", timer.remaining); // Output: 1000

Example usage:

timer.pause();
// Do some stuff...
timer.resume();
Release Statement This article is reprinted at: 1729595895 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3