Home  >  Article  >  Web Front-end  >  How Can I Control Timeout Execution and Determine Remaining Time in JavaScript?

How Can I Control Timeout Execution and Determine Remaining Time in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-22 20:47:12286browse

How Can I Control Timeout Execution and Determine Remaining Time in JavaScript?

Pausing and Resuming Timeouts in JavaScript

When working with JavaScript, it can be necessary to control the flow of asynchronous operations such as timeouts. Here, we explore ways to pause and resume active timeouts, as well as retrieve the remaining time on the current timeout.

Pausing and Resuming Timeouts

To pause a timeout, you can utilize a wrapper function that intercepts the window.setTimeout call and provides the necessary functionality. The wrapper function, Timer, takes a callback function and a delay as arguments and handles the pausing, resuming, and tracking of the remaining time.

<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>

To use this wrapper, instantiate a Timer object and call its pause() and resume() methods as needed.

Retrieving Remaining Time

To obtain the remaining time on the current timeout, one way is to store the start time when the timeout is set and calculate the difference between the current time and the start time when pausing.

<code class="javascript">var start = Date.now();
var t = setTimeout("dosomething()", 5000);
var remaining = (start + 5000) - Date.now();</code>

However, it's important to note that if the timeout has been paused and resumed, this calculation may not be accurate. In the Timer wrapper function provided earlier, the remaining time is tracked and updated accordingly, providing a more reliable method for retrieving the remaining time.

The above is the detailed content of How Can I Control Timeout Execution and Determine Remaining Time 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