Home >Web Front-end >JS Tutorial >How Can You Control and Track Timeouts in JavaScript?

How Can You Control and Track Timeouts in JavaScript?

DDD
DDDOriginal
2024-10-22 19:22:33625browse

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.

<code class="javascript">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();
};</code>

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.

<code class="javascript">var timer = new Timer(function() {
    alert("Done!");
}, 1000);

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

Example usage:

<code class="javascript">timer.pause();
// Do some stuff...
timer.resume();</code>

The above is the detailed content of How Can You Control and Track Timeouts in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn