귀하의 방법이 작동하지 않는 때문에 문이 한 번만 평가되는 경우; 문서로드시. 이를 해결하려면 totalSeconds가 업데이트 될 때마다 점검되는 콜백을 추가해야합니다.
여기 내 해결책이 있습니다. fiddle here
당신과 같이, Clock.at(time, callback)
를 사용하여 기능을 추가 할 수
Clock.at (10, 함수() {/ * 10초 * /} 통과); 문이 totalSeconds
이 setInterval
에 의해 업데이트 될 때마다 호출 할 필요가있는 경우
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,
});
}
};
당신 솔루션이 첫 번째 호출 후 콜백마다 두 번째를 호출하고, 하나의 콜백을 허용합니다. 나는 이것이 OP를 위해 바람직하지 않다고 가정합니다. – Indy
@ 아이디 업데이트 된 답변으로 demo2를 보시기 바랍니다. –
추가 질문 :'resume' 함수에서 인수는 비어 있어야합니다. if (! this.interval) this.시작(); ' – cqcn1991