Home >Web Front-end >JS Tutorial >How Can You Control and Track 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!