不就是利用 window 物件的 setTimeout 方法嗎?沒錯!如果你在一個應用裡常常要「延時執行某函數」,那麼基於 DRY 原則,可以針對 Function 全域物件進行擴充,為函數增加一個延時方法如 delay,這會讓你的程式碼更簡潔有效。
為 Function 物件增加 delay 方法如下:
Function.prototype.delay = function (this1, timeout) {
this1 = this1 || null;
timeout = timeout || 0;
var _this = this;
var args = [];
// 取得參數,註:第 1、第 2 個參數是保留參數
switch (arguments.length) {
case 1:
timeout = parseInt(arguments[0]);
timeout = isNaN(timeout) ? 0 : timeout;
timeout = timeout < 0 ? 0 : timeout;
break;
default:
for (var i = 0; i < arguments.length; i++) {
if (i > 1) { args.push(arguments[i]); }
}
break;
}
var proxy = function () {
_this.apply(this1, args);
};
return window.setTimeout(proxy, timeout);
};
在 Firefox 的 Firebug 主控台下測試:
var xx = function (n) {
this.name = n;
};
xx.prototype.hi = function (a, b) {
console.log(this.name + "-" + a + "-" + b);
};
var xx1 = new xx("levin");
var t = xx1.hi.delay(xx1, 1000, "cocoa", "yoyo");
xx1.hi("guluglu", "jigujigu");
這個 delay 方法的第一個參數用來指定 this 指向,第二個參數是延遲的毫秒數,其後則是要傳給原函數的參數。透過 apply 動態套用,讓任何函數都能優雅地具備延時執行能力,同時回傳 setTimeout 的 id 以便日後清除。