Answers:
您可以这样包装window.setTimeout
,我认为这与您在问题中建议的内容类似:
var Timer = function(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= Date.now() - start;
};
this.resume = function() {
start = Date.now();
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
};
this.resume();
};
var timer = new Timer(function() {
alert("Done!");
}, 1000);
timer.pause();
// Do some stuff...
timer.resume();
setTimeout()
并不在Internet Explorer中工作<= 9
timer.resume(); timer.resume();
,最终将导致两个超时并行发生。这就是为什么您想在履历表的开头clearTimeout(timerId)
先进行if (timerId) return;
短路或短路的原因。
var timerId, start, remaining;
在Class范围之外,然后再添remaining = delay;
加到内部以捕获参数。像魅力一样运作!
if (blah) { ... }
?
这样的事情应该可以解决问题。
function Timer(fn, countdown) {
var ident, complete = false;
function _time_diff(date1, date2) {
return date2 ? date2 - date1 : new Date().getTime() - date1;
}
function cancel() {
clearTimeout(ident);
}
function pause() {
clearTimeout(ident);
total_time_run = _time_diff(start_time);
complete = total_time_run >= countdown;
}
function resume() {
ident = complete ? -1 : setTimeout(fn, countdown - total_time_run);
}
var start_time = new Date().getTime();
ident = setTimeout(fn, countdown);
return { cancel: cancel, pause: pause, resume: resume };
}
Tim Downs 答案的略微修改版本。但是,由于Tim 撤消了我的编辑,所以我必须自己回答。我的解决方案使得可以将多余的参数arguments
用作第三(3、4、5 ...)参数并清除计时器:
function Timer(callback, delay) {
var args = arguments,
self = this,
timer, start;
this.clear = function () {
clearTimeout(timer);
};
this.pause = function () {
this.clear();
delay -= new Date() - start;
};
this.resume = function () {
start = new Date();
timer = setTimeout(function () {
callback.apply(self, Array.prototype.slice.call(args, 2, args.length));
}, delay);
};
this.resume();
}
如Tim所述,多余的参数在中不可用IE lt 9
,但是我做了一些努力,以便在oldIE
。
用法: new Timer(Function, Number, arg1, arg2, arg3...)
function callback(foo, bar) {
console.log(foo); // "foo"
console.log(bar); // "bar"
}
var timer = new Timer(callback, 1000, "foo", "bar");
timer.pause();
document.onclick = timer.resume;
在的上下文中setTimeout
,“暂停”和“恢复”并没有多大意义,这是一次性的事情。你是说setInterval
吗 如果是这样,则不能,您不能暂停它,只能取消它(clearInterval
),然后重新安排它的时间。所有这些的详细信息在规范的“ 计时器”部分。
// Setting
var t = setInterval(doSomething, 1000);
// Pausing (which is really stopping)
clearInterval(t);
t = 0;
// Resuming (which is really just setting again)
t = setInterval(doSomething, 1000);
超时很容易找到解决方案,但是间隔有些棘手。
我提出了以下两个类来解决此问题:
function PauseableTimeout(func, delay){
this.func = func;
var _now = new Date().getTime();
this.triggerTime = _now + delay;
this.t = window.setTimeout(this.func,delay);
this.paused_timeLeft = 0;
this.getTimeLeft = function(){
var now = new Date();
return this.triggerTime - now;
}
this.pause = function(){
this.paused_timeLeft = this.getTimeLeft();
window.clearTimeout(this.t);
this.t = null;
}
this.resume = function(){
if (this.t == null){
this.t = window.setTimeout(this.func, this.paused_timeLeft);
}
}
this.clearTimeout = function(){ window.clearTimeout(this.t);}
}
function PauseableInterval(func, delay){
this.func = func;
this.delay = delay;
this.triggerSetAt = new Date().getTime();
this.triggerTime = this.triggerSetAt + this.delay;
this.i = window.setInterval(this.func, this.delay);
this.t_restart = null;
this.paused_timeLeft = 0;
this.getTimeLeft = function(){
var now = new Date();
return this.delay - ((now - this.triggerSetAt) % this.delay);
}
this.pause = function(){
this.paused_timeLeft = this.getTimeLeft();
window.clearInterval(this.i);
this.i = null;
}
this.restart = function(sender){
sender.i = window.setInterval(sender.func, sender.delay);
}
this.resume = function(){
if (this.i == null){
this.i = window.setTimeout(this.restart, this.paused_timeLeft, this);
}
}
this.clearInterval = function(){ window.clearInterval(this.i);}
}
这些可以这样实现:
var pt_hey = new PauseableTimeout(function(){
alert("hello");
}, 2000);
window.setTimeout(function(){
pt_hey.pause();
}, 1000);
window.setTimeout("pt_hey.start()", 2000);
本示例将设置一个可暂停的超时(pt_hey),该超时时间安排为在两秒钟后提醒“嘿”。一秒钟后,另一个超时会暂停pt_hey。第二次超时将在两秒钟后恢复pt_hey。pt_hey运行一秒钟,暂停一秒钟,然后恢复运行。pt_hey在三秒钟后触发。
现在需要更棘手的间隔
var pi_hey = new PauseableInterval(function(){
console.log("hello world");
}, 2000);
window.setTimeout("pi_hey.pause()", 5000);
window.setTimeout("pi_hey.resume()", 6000);
本示例设置一个可暂停的时间间隔(pi_hey),以每两秒钟在控制台中写入“ hello world”。超时会在五秒钟后暂停pi_hey。六秒后,另一个超时将恢复pi_hey。因此pi_hey将触发两次,运行一秒钟,暂停一秒钟,运行一秒钟,然后每2秒继续触发一次。
clearTimeout()和clearInterval()
pt_hey.clearTimeout();
并pi_hey.clearInterval();
用作清除超时和时间间隔的简便方法。
getTimeLeft()
pt_hey.getTimeLeft();
并pi_hey.getTimeLeft();
会返回多少毫秒,直到安排下一次触发发生为止。
setInterval
?我认为简单if(!true) return;
就能解决问题,还是我错了?
我需要计算经过和剩余的时间才能显示进度条。使用公认的答案并不容易。对于此任务,“ setInterval”优于“ setTimeout”。因此,我创建了可在任何项目中使用的Timer类。
https://jsfiddle.net/ashraffayad/t0mmv853/
'use strict';
//Constructor
var Timer = function(cb, delay) {
this.cb = cb;
this.delay = delay;
this.elapsed = 0;
this.remaining = this.delay - self.elapsed;
};
console.log(Timer);
Timer.prototype = function() {
var _start = function(x, y) {
var self = this;
if (self.elapsed < self.delay) {
clearInterval(self.interval);
self.interval = setInterval(function() {
self.elapsed += 50;
self.remaining = self.delay - self.elapsed;
console.log('elapsed: ' + self.elapsed,
'remaining: ' + self.remaining,
'delay: ' + self.delay);
if (self.elapsed >= self.delay) {
clearInterval(self.interval);
self.cb();
}
}, 50);
}
},
_pause = function() {
var self = this;
clearInterval(self.interval);
},
_restart = function() {
var self = this;
self.elapsed = 0;
console.log(self);
clearInterval(self.interval);
self.start();
};
//public member definitions
return {
start: _start,
pause: _pause,
restart: _restart
};
}();
// - - - - - - - - how to use this class
var restartBtn = document.getElementById('restart');
var pauseBtn = document.getElementById('pause');
var startBtn = document.getElementById('start');
var timer = new Timer(function() {
console.log('Done!');
}, 2000);
restartBtn.addEventListener('click', function(e) {
timer.restart();
});
pauseBtn.addEventListener('click', function(e) {
timer.pause();
});
startBtn.addEventListener('click', function(e) {
timer.start();
});
/复活
使用y类语法糖的ES6版本💋
(稍作修改:添加了start())
class Timer {
constructor(callback, delay) {
this.callback = callback
this.remainingTime = delay
this.startTime
this.timerId
}
pause() {
clearTimeout(this.timerId)
this.remainingTime -= new Date() - this.startTime
}
resume() {
this.startTime = new Date()
clearTimeout(this.timerId)
this.timerId = setTimeout(this.callback, this.remainingTime)
}
start() {
this.timerId = setTimeout(this.callback, this.remainingTime)
}
}
// supporting code
const pauseButton = document.getElementById('timer-pause')
const resumeButton = document.getElementById('timer-resume')
const startButton = document.getElementById('timer-start')
const timer = new Timer(() => {
console.log('called');
document.getElementById('change-me').classList.add('wow')
}, 3000)
pauseButton.addEventListener('click', timer.pause.bind(timer))
resumeButton.addEventListener('click', timer.resume.bind(timer))
startButton.addEventListener('click', timer.start.bind(timer))
<!doctype html>
<html>
<head>
<title>Traditional HTML Document. ZZz...</title>
<style type="text/css">
.wow { color: blue; font-family: Tahoma, sans-serif; font-size: 1em; }
</style>
</head>
<body>
<h1>DOM & JavaScript</h1>
<div id="change-me">I'm going to repaint my life, wait and see.</div>
<button id="timer-start">Start!</button>
<button id="timer-pause">Pause!</button>
<button id="timer-resume">Resume!</button>
</body>
</html>
您可以查看clearTimeout()
或暂停取决于在达到特定条件时设置的全局变量。就像按下一个按钮一样。
<button onclick="myBool = true" > pauseTimeout </button>
<script>
var myBool = false;
var t = setTimeout(function() {if (!mybool) {dosomething()}}, 5000);
</script>
您还可以通过事件来实现它。
无需计算时差,而是开始和停止侦听一直在后台运行的“ tick”事件:
var Slideshow = {
_create: function(){
this.timer = window.setInterval(function(){
$(window).trigger('timer:tick'); }, 8000);
},
play: function(){
$(window).bind('timer:tick', function(){
// stuff
});
},
pause: function(){
$(window).unbind('timer:tick');
}
};
如果您使用的是jquery,请查看$ .doTimeout插件。这是对setTimeout的巨大改进,其中包括让您使用指定的单个字符串ID跟踪超时,并且每次设置时该字符串ID都不会更改,并实现了轻松的取消,轮询循环和反跳操作,以及更多。我最常用的jquery插件之一。
不幸的是,它不支持开箱即用的暂停/继续。为此,您可能需要包装或扩展$ .doTimeout,大概与接受的答案类似。
我需要能够暂停setTimeout()以实现类似幻灯片的功能。
这是我自己的可暂停计时器的实现。它整合了在Tim Down的答案中看到的评论,例如更好的停顿(内核的评论)和原型制作的形式(Umur Gedik的评论)。
function Timer( callback, delay ) {
/** Get access to this object by value **/
var self = this;
/********************* PROPERTIES *********************/
this.delay = delay;
this.callback = callback;
this.starttime;// = ;
this.timerID = null;
/********************* METHODS *********************/
/**
* Pause
*/
this.pause = function() {
/** If the timer has already been paused, return **/
if ( self.timerID == null ) {
console.log( 'Timer has been paused already.' );
return;
}
/** Pause the timer **/
window.clearTimeout( self.timerID );
self.timerID = null; // this is how we keep track of the timer having beem cleared
/** Calculate the new delay for when we'll resume **/
self.delay = self.starttime + self.delay - new Date().getTime();
console.log( 'Paused the timer. Time left:', self.delay );
}
/**
* Resume
*/
this.resume = function() {
self.starttime = new Date().getTime();
self.timerID = window.setTimeout( self.callback, self.delay );
console.log( 'Resuming the timer. Time left:', self.delay );
}
/********************* CONSTRUCTOR METHOD *********************/
/**
* Private constructor
* Not a language construct.
* Mind var to keep the function private and () to execute it right away.
*/
var __construct = function() {
self.starttime = new Date().getTime();
self.timerID = window.setTimeout( self.callback, self.delay )
}(); /* END __construct */
} /* END Timer */
例:
var timer = new Timer( function(){ console.log( 'hey! this is a timer!' ); }, 10000 );
timer.pause();
要测试代码,请使用timer.resume()
和timer.pause()
几次,并检查还剩下多少时间。(确保您的控制台已打开。)
到位的setTimeout()的使用对象是一样容易更换timerID = setTimeout( mycallback, 1000)
用timer = new Timer( mycallback, 1000 )
。然后timer.pause()
,timer.resume()
您可以使用。
function delay (ms) { return new Promise(resolve => setTimeout(resolve, s)); }
“异步”工作演示,网址: zarsoft.info
基于评分最高的答案的打字稿实现
/** Represents the `setTimeout` with an ability to perform pause/resume actions */
export class Timer {
private _start: Date;
private _remaining: number;
private _durationTimeoutId?: NodeJS.Timeout;
private _callback: (...args: any[]) => void;
private _done = false;
get done () {
return this._done;
}
constructor(callback: (...args: any[]) => void, ms = 0) {
this._callback = () => {
callback();
this._done = true;
};
this._remaining = ms;
this.resume();
}
/** pauses the timer */
pause(): Timer {
if (this._durationTimeoutId && !this._done) {
this._clearTimeoutRef();
this._remaining -= new Date().getTime() - this._start.getTime();
}
return this;
}
/** resumes the timer */
resume(): Timer {
if (!this._durationTimeoutId && !this._done) {
this._start = new Date;
this._durationTimeoutId = setTimeout(this._callback, this._remaining);
}
return this;
}
/**
* clears the timeout and marks it as done.
*
* After called, the timeout will not resume
*/
clearTimeout() {
this._clearTimeoutRef();
this._done = true;
}
private _clearTimeoutRef() {
if (this._durationTimeoutId) {
clearTimeout(this._durationTimeoutId);
this._durationTimeoutId = undefined;
}
}
}
您可以像下面那样在服务器端使setTimeout暂停(Node.js)
const PauseableTimeout = function(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function() {
global.clearTimeout(timerId);
remaining -= Date.now() - start;
};
this.resume = function() {
start = Date.now();
global.clearTimeout(timerId);
timerId = global.setTimeout(callback, remaining);
};
this.resume();
};
你可以检查它如下
var timer = new PauseableTimeout(function() {
console.log("Done!");
}, 3000);
setTimeout(()=>{
timer.pause();
console.log("setTimeout paused");
},1000);
setTimeout(()=>{
console.log("setTimeout time complete");
},3000)
setTimeout(()=>{
timer.resume();
console.log("setTimeout resume again");
},5000)
我认为您找不到比clearTimeout更好的东西。无论如何,您总是可以在以后安排另一个超时,而不是“继续”。
如果要隐藏多个div,则可以使用setInterval
和一个循环来执行以下操作:
<div id="div1">1</div><div id="div2">2</div>
<div id="div3">3</div><div id="div4">4</div>
<script>
function hideDiv(elm){
var interval,
unit = 1000,
cycle = 5,
hide = function(){
interval = setInterval(function(){
if(--cycle === 0){
elm.style.display = 'none';
clearInterval(interval);
}
elm.setAttribute('data-cycle', cycle);
elm.innerHTML += '*';
}, unit);
};
elm.onmouseover = function(){
clearInterval(interval);
};
elm.onmouseout = function(){
hide();
};
hide();
}
function hideDivs(ids){
var id;
while(id = ids.pop()){
hideDiv(document.getElementById(id));
}
}
hideDivs(['div1','div2','div3','div4']);
</script>