我想在特定时间后触发一些事件。计时器应该是可暂停的。 这是代码: http://jsfiddle.net/xsH8v/
问题是我怎样才能触发这个
if (Clock.totalSeconds >= givenTime){
alert('time is up!');
}
我把它放在 document.ready
里了。但是当时间到了时它不会被解雇。我认为问题在于根本没有调用该函数。如果是这样,我该如何触发它?
最佳答案
您的方法不起作用,因为 if 语句只计算一次;在文档加载时。要解决此问题,您需要添加每次更新 totalSeconds 时都会检查的回调。
这是我的解决方案; fiddle here
您可以使用 Clock.at(time, callback)
添加函数,如下所示:
Clock.at(10, function() {/* 10 秒过去了 */});
var Clock = {
totalSeconds: 0,
handlers: [],
start: function () {
var self = this;
this.interval = setInterval(function () {
self.totalSeconds += 1;
sec = parseInt(self.totalSeconds % 60)
min = Math.floor(self.totalSeconds / 60 % 60)
hour = Math.floor(self.totalSeconds / 3600)
$("#hour").text(hour);
$("#min").text(min);
$("#sec").text(sec);
// Fire each expired handlers
self.handlers = self.handlers.filter(function(handler) {
if (self.totalSeconds >= handler.time) {
// Fire the handler then remove it
handler.func();
return false;
}
return true;
})
}, 1000);
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
if (!this.interval) this.start();
},
at: function(time, handler) {
// Handle expired handlers
if (this.totalSeconds >= time) handler();
// Add the handler to the queue
this.handlers.push({
time: time,
func: handler,
});
}
};
关于javascript - js : trigger a timing event after pause/resume,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21794971/