Home > Web Front-end > JS Tutorial > body text

How to Pause and Resume Timeouts in JavaScript Efficiently?

Barbara Streisand
Release: 2024-10-23 00:18:03
Original
940 people have browsed it

How to Pause and Resume Timeouts in JavaScript Efficiently?

Pausing and Resuming JavaScript Timeouts

When working with setTimeouts in JavaScript, the ability to pause and resume them can be useful in various scenarios. One might encounter a situation where a delay has been configured, but a pause is necessary before execution or to wait for an asynchronous operation to complete.

Pausing and Resuming Timeouts with a Custom Wrapper

Instead of storing the current time and calculating the remaining duration, it's possible to create a custom wrapper around window.setTimeout that provides pause and resume functionality. This approach offers a more elegant and reusable solution:

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();
};
Copy after login

This custom Timer class allows you to pause and resume timeouts as needed. To use it, initialize it with the callback function and delay, and then call the pause() or resume() methods as required.

Example:

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

timer.pause();
// Perform asynchronous operations or other tasks
timer.resume();
Copy after login

Note: This custom wrapper doesn't provide a way to retrieve the remaining time on the paused timer. Alternatively, one could implement a more comprehensive wrapper that tracks the remaining time and provides a getTimeRemaining() method.

The above is the detailed content of How to Pause and Resume Timeouts in JavaScript Efficiently?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!