atama null
.
Böyle bir sınıf bu gibi görünebilir:
/** class Timer **/
var Timer = function(delayMs, callbackFunc) {
this.delayMs = delayMs;
this.callbackFunc = callbackFunc;
this.timerState = 'new';
}
Timer.prototype.start = function() {
if(this.tmr) return;
var self = this;
this.timerState = 'running';
this.tmr = setTimeout(function() { self._handleTmr(); }, this.delayMs);
}
Timer.prototype.cancel = function() {
if(! this.tmr) return;
clearTimeout(this.tmr);
this.tmr = null;
this.timerState = 'canceled';
}
Timer.prototype._handleTmr = function() {
this.tmr = null;
this.timerState = 'completed';
this.callbackFunc();
}
Ben de kolayca zamanlayıcı "tamamlandı" veya "iptal" olup olmadığını belirlemek izin verecek bir timerState
niteliğini dahil ettik.
Böyle kullanmak olacaktır:
var t = new Timer(500, function() {
alert('timer completed');
});
t.start();
// do whatever...
// now cancel the timer if it hasn't completed yet.
t.cancel();
// maybe you do some other stuff...
// then check the timerState, and act accordingly.
//
if(t.timerState == 'canceled') {
alert("the timer was canceled!");
} else {
alert("the timer completed uneventfully.");
}
Sen
(. Örn zamanlayıcı tekrarlayarak/durdurma/devam ettirme, vb başlatmak) de gerekirse ek işlevler eklemek için aynı temel fikri uzatabilirsiniz
Eğer jQuery ya da diğer JS çerçevelerinden biri böyle bir şey olsaydı ben hiç şaşırmam. Varsa, jQuery uzmanları biliyor mu? – MatrixFrog
Bu gerçekten kapsamlıdır. Teşekkürler! – lai