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.
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();
};
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.
var timer = new Timer(function() {
alert("Done!");
}, 1000);
console.log("Time remaining:", timer.remaining); // Output: 1000
Example usage:
timer.pause();
// Do some stuff...
timer.resume();
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3