Si usted está buscando algo más formal, se podría construir Javascript clase que encapsula la funcionalidad setTimeout
/clearTimeout
.
una clase de este tipo podría ser algo como esto:
/** 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();
}
También he incluido un atributo timerState
que le permiten determinar fácilmente si el temporizador fue "terminado" o "cancelar".
Se podría utilizar de esta manera:
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.");
}
se puede extender la misma idea básica para incluir funcionalidad adicional si lo necesita (por ejemplo, la repetición de temporizador, inicio/parada/hoja de vida, etc.)
No me sorprendería en absoluto si jQuery o uno de los otros frameworks JS tuviera algo como esto. ¿Algún experto de jQuery sabe si existe o no? – MatrixFrog
Esto es realmente completo. ¡Gracias! – lai