असाइन null
टाइमर के लिए आप कुछ और अधिक औपचारिक, आप जावास्क्रिप्ट वर्ग कि setTimeout
/clearTimeout
कार्यक्षमता समाहित बना सकते हैं की तलाश में हैं।
इस तरह के एक वर्ग कुछ इस तरह दिख सकता है:
/** 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();
}
मैं भी एक timerState
विशेषता है कि आप आसानी से निर्धारित टाइमर गया था "पूरा" या "रद्द" दिया जाएगा शामिल किया है।
आप इस तरह यह प्रयोग करेंगे:
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.");
}
आप एक ही मूल विचार का विस्तार कर सकते अतिरिक्त कार्यक्षमता शामिल करने के लिए यदि आप इसे की जरूरत है (उदाहरण के लिए टाइमर दोहरा, प्रारंभ/बंद/फिर से शुरू, आदि।)
स्रोत
2010-10-26 07:04:04
अगर मैं jQuery या अन्य जेएस ढांचे में से एक ऐसा कुछ था तो मुझे आश्चर्य नहीं होगा। किसी भी jQuery विशेषज्ञों को पता है कि यह मौजूद है या नहीं? – MatrixFrog
यह वास्तव में व्यापक है। धन्यवाद! – lai