When working with JavaScript, it can be necessary to control the flow of asynchronous operations such as timeouts. Here, we explore ways to pause and resume active timeouts, as well as retrieve the remaining time on the current timeout.
To pause a timeout, you can utilize a wrapper function that intercepts the window.setTimeout call and provides the necessary functionality. The wrapper function, Timer, takes a callback function and a delay as arguments and handles the pausing, resuming, and tracking of the remaining time.
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();
};
To use this wrapper, instantiate a Timer object and call its pause() and resume() methods as needed.
To obtain the remaining time on the current timeout, one way is to store the start time when the timeout is set and calculate the difference between the current time and the start time when pausing.
var start = Date.now();
var t = setTimeout("dosomething()", 5000);
var remaining = (start + 5000) - Date.now();
However, it's important to note that if the timeout has been paused and resumed, this calculation may not be accurate. In the Timer wrapper function provided earlier, the remaining time is tracked and updated accordingly, providing a more reliable method for retrieving the remaining time.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3