■ Kazuho@Cybozu Labs: setTimeout をオブジェクト指向にしてみる
http://labs.cybozu.co.jp/blog/kazuho/archives/2006/12/oo-settimeout.php
Function.prototype.applyTimeout = function (ms, self, args) {
var f = this;
return setTimeout(
function () {
f.apply(self, args);
},
ms);
};
Function.prototype.callTimeout = function (ms, self) {
return this.applyTimeout(
ms,
self,
Array.prototype.slice.call(arguments, 2));
};
Function.prototype.applyInterval = function (ms, self, args) {
var f = this;
return setInterval(
function () {
f.apply(self, args);
},
ms);
};
Function.prototype.callInterval = function (ms, self) {
return this.applyInterval(
ms,
self,
Array.prototype.slice.call(arguments, 2));
};
使い方は
this.timer_id = foo.bar.applyInterval(1000, foo, [ hoge ]); // setInterval & apply
セットした setInterval を解除するには
clearInterval(this.timer_id);
参考:http://blog.livedoor.jp/dankogai/archives/50714622.html