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
Release: 2024-10-22 19:22:33
Original
641 people have browsed it

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>
Copy after login

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>
Copy after login

Example usage:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template