原生 setTimeout 與 setInterval 已經堪用,但jQuery Timers 這支插件在此之上做了三件事:讓時間寫法變直觀('1s'、'2das')、讓計時器可以命名以便精準關閉、以及讓計時器綁在 jQuery 物件上隨元素一併管理。作者是 Blair Mitchelmore,版本 1.2。
插件為 $.fn 加了錄三個方法:
jQuery.fn.extend({
everyTime: function(interval, label, fn, times) {
return this.each(function() {
jQuery.timer.add(this, interval, label, fn, times);
});
},
oneTime: function(interval, label, fn) {
return this.each(function() {
jQuery.timer.add(this, interval, label, fn, 1);
});
},
stopTime: function(label, fn) {
return this.each(function() {
jQuery.timer.remove(this, label, fn);
});
}
});
對應的簽名如下:
everyTime(時間間隔, [計時器名稱], 函式, [次數限制], [等待函式完成])oneTime(時間間隔, [計時器名稱], 函式)stopTime([計時器名稱], [函式])時間字串由「數字 + 單位」組成,插件內部靠一個 powers 表換算成毫秒:
powers: {
'ms': 1, // 毫秒
'cs': 10, // 厘秒
'ds': 100, // 分秒
's': 1000, // 秒
'das': 10000, // 十秒
'hs': 100000, // 百秒
'ks': 1000000 // 千秒
}
也就是說 '2das' 是 20 秒、'1hs' 是 100 秒、'1ks' 是 1000 秒。想自訂單位(例如加上分鐘 'm': 60000),直接改這張表即可。解析的部分由 timeParse 負責:
regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
timeParse: function(value) {
if (value == undefined || value == null) { return null; }
var result = this.regex.exec(jQuery.trim(value.toString()));
if (result[2]) {
var num = parseFloat(result[1]);
var mult = this.powers[result[2]] || 1;
return num * mult;
}
return value;
}
// 每 1 秒執行 test()
function test(){ /* do something */ }
$('body').everyTime('1s', test);
// 每 1 秒執行匿名函式
$('body').everyTime('1s', function(){ /* do something */ });
// 命名為 A,方便日後精準停止
$('body').everyTime('1s', 'A', function(){ /* do something */ });
// 每 20 秒執行,最多 5 次,命名為 B
$('body').everyTime('2das', 'B', function(){ /* do something */ }, 5);
// 每 20 秒執行、無次數限制,且若上次的函式還沒跑完則先等它結束
$('body').everyTime('2das', 'C', function(){
// 執行一個可能超過 20 秒的程式
}, 0, true);
最後那個「等待函式完成」參數很實用。預設情況下 setInterval 是不管上次跑完沒、時間到就觸發,若你的函式可能超過間隔時間,就會造成多個執行緒同時跑同一段邏輯。把第五個參數設為 true 可以避免這種重入。
// 10 秒後執行一次
$('body').oneTime('1das', function(){ /* do something */ });
// 100 秒後執行一次,命名為 D
$('body').oneTime('1hs', 'D', function(){ /* do something */ });
// 停止 $('body') 上的所有計時器
$('body').stopTime();
// 只停止名稱為 A 的計時器
$('body').stopTime('A');
// 停止所有會呼叫 test() 的計時器
$('body').stopTime(test);
點擊關閉鈕後等 1 秒才真的隱藏視窗,期間若使用者改點取消,就把計時器停掉:
$("#close-button").click(function() {
$(this).oneTime(1000, function() {
$(this).parent(".main-window").hide();
});
});
$("#cancel-button").click(function() {
$("#close-button").stopTime();
});
插件原始碼最後有一段全域清理,避免頁面跳走時殘留計時器造成記憶體洩漏:
jQuery(window).bind("unload", function() {
jQuery.each(jQuery.timer.global, function(index, item) {
jQuery.timer.remove(item);
});
});
internally 計時器是存在 jQuery.data(element, "jQuery.timer") 裡的,用 element 當索引、label 當分組、fn.timerID 當唯一鍵,因此同一個元素上可以並存多個互不干擾的計時器。這也是為什麼命名如此重要——不命名的話,停止時就只能整批清掉或靠函式參照比對。