2011年5月3日

JQuery Timer

老實說,我並不是很常寫複雜的javascript。最近手癢把一個原來要用flash完成的自動換圖,改用javascript寫。由於對 setInterval 深惡痛覺,就找了半天看有沒有Timer可用。找了半天,發現大部分的都用callback,也有closure的問題,再找下去也不是辦法,就決定自己寫一個。

function Timer(delay, repeatCount) {
this.delay = delay;
this.repeatCount = repeatCount;
this.currentCount = 0;
this.timeHandle = 0;
this.running = false;
this.start = function() {
this.timeHandle = setInterval(Timer.delegate(this, this._timer), this.delay);
running = true;
}
this.reset = function() {
this.stop();
this.currentCount = 0;
}
this.stop = function() {
if (this.timeHandle != 0) {
clearInterval(this.timeHandle);
this.timeHandle = 0;
}
this.running = false;
}
this._timer = function() {
$(this).trigger($.Event("timer"));
if (this.repeatCount > 0) {
this.currentCount++;
if (this.currentCount >= this.repeatCount) {
this.reset();
}
}
}
}
Timer.delegate = function(obj, func) {
var f = function() {
var target = arguments.callee.target;
var func = arguments.callee.func;
return func.apply(target, arguments);
};
f.target = obj;
f.func = func;
return f;
}

使用的方式:需要先載入jquery(只是要一個能 trigger event 的 framework)。用 bind("timer", handler) 去接收timer事件。

var ct = 0;
function timer_tick(event) {
ct++;
alert(ct + "," + this.currentCount);
}

var timer = new Timer(5000, 3);
$(timer).bind("timer", timer_tick);
timer.start();

這個是照著flash.utils.Timer刻的,用法也幾乎相同(用javascript模仿read-only,實在太囉唆了,所以沒做),不熟悉的人可以去 http://help.adobe.com/zh_TW/AS3LCR/Flash_10.0/flash/utils/Timer.html 看。至於這麼一點功能卻要 load 一個龐大的 jquery,是不是值得,就請大家自己判斷了。

沒有留言:

張貼留言