0
如果我有以下代碼:javascript:如何驗證計時器屬性?
var myfunc = function() { alert('wow'); };
var t=setTimeout(myfunc, 300);
有什麼我可以存儲在t
的ID做驗證計時器的持續時間和回調?我試圖直接驗證計時器的屬性,所以我不必實際運行它,直到單元測試超時。
如果我有以下代碼:javascript:如何驗證計時器屬性?
var myfunc = function() { alert('wow'); };
var t=setTimeout(myfunc, 300);
有什麼我可以存儲在t
的ID做驗證計時器的持續時間和回調?我試圖直接驗證計時器的屬性,所以我不必實際運行它,直到單元測試超時。
不行,不能做。
你可以做的反而是跟蹤它們不同,這樣的事情:
var timeouts = [{
fn: myfunc,
timeout: 300
}];
for(var i = 0; i < timeouts.length; i++){
timeouts[i].id = window.setTimeout(timeouts[i].fn, timeouts[i].timeout);
}
返回的ID是內部的瀏覽器,所以你不能做它。但因爲你知道時間和回調,當你啓動計時器,你也可以同樣包裹了整個事情的Timer
的類,它爲你的一切:
function Timer(callback, timeout) {
this.callback = callback;
this.timeout = timeout;
this.id = window.setTimeout(callback, timeout);
}
Timer.prototype.cancel = function() {
window.clearTimeout(this.id);
}
Timer.prototype.fire = function() {
this.cancel();
this.callback();
}
然後你只需創建定時器並訪問像它們的屬性這個:
t = new Timer(myfunc, 300);
alert(t.timeout);