Home  >  Article  >  Web Front-end  >  How to Pause and Resume setTimeout() in JavaScript?

How to Pause and Resume setTimeout() in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 00:55:03254browse

How to Pause and Resume setTimeout() in JavaScript?

Pausing and Resuming setTimeout() in JavaScript

In JavaScript, setTimeout() allows you to schedule a function to be executed after a specified delay. However, you may encounter scenarios where you need to pause or resume the execution of the timeout.

Pausing and Resuming setTimeout()

To pause a running timeout, you can use the window.clearTimeout() function. It takes the ID of the timeout to be cleared as an argument. After pausing, you can resume the timeout using the timer.resume() method.

Custom Timer with Pause/Resume Functionality

An alternative approach is to create a custom timer object with pause and resume methods. This allows you to control the timeout more directly. Here's an example of such a timer:

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

Getting Time Remaining on setTimeout()

Unfortunately, there's no built-in way to get the remaining time on a setTimeout(). However, you can use the approach described above, where you manually store the start time and calculate the remaining time when pausing the timer.

By wrapping setTimeout() in a custom timer object or using the manual time calculation approach, you can achieve pause and resume functionality for your timeouts in JavaScript.

The above is the detailed content of How to Pause and Resume setTimeout() 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