1
我製作了一個您必須使用實例的輪詢系統,因此可以讓多個輪詢器同時運行。當所有引用都丟失時從對象實例開始停止超時
輪詢使用setTimeout按照定義的輪詢速率延遲每個請求。
這是一個非常簡化的版本:
function Poller(url, rate, callback) {
var timeoutReference = null;
var public = {
poll: function() {
/* Request here i.e. $.GET(....)
calling callback with recieved data on success */
console.log("Poller running");
timeoutReference = setTimeout(public.poll, rate);
},
stop: function() {
clearTimeout(timeoutReference);
}
}
return public;
}
var poller1 = new Poller('http://www.site.com/feed', 5000, readData);
poller1.poll();
現在,如果我做
poller1 = null;
超時仍在運行,並且將永遠運行。我需要做
poller1.stop();
poller1 = null;
使其按預期工作。
有什麼方法可以在所有引用丟失時清除超時,因此省略了調用poller1.stop()的需要;在未參考實例之前?
我想我真正在尋找的是一個old-skool析構函數,當所有引用都丟失時被調用,但我知道JavaScript中沒有這樣的東西。不是嗎? – tomtastico 2011-04-16 12:59:24