[英]How can I rewrite alternative $setTimeout function such that it is easier to read?
最初,在AngularJS中,我有一個要定期調用的函數。 因此,我使用$setInterval
函數來執行此操作。 但是,這樣做后,我注意到即使離開頁面,該功能仍會繼續運行,並在控制台中完全充滿錯誤,直到我導航回與該功能相關的頁面。 我用在這里找到的解決方案替換了$setInterval
函數。 這個家伙寫了$setInterval
全新版本。 它顯示為:
function interval(func, wait, times) {
var interv = function(w,t){
return function(){
if(typeof t === "undefined" || t--> 0){
setTimeout(interv, w);
try{
func.call(null);
}catch(e){
t = 0;
throw e.toString();
}
}
};
}(wait,times);
setTimeout(interv,wait);
};
我基本上將我的函數稱為:
interval($scope.setValue, 100);
該功能完全可以按照我的意願工作,並且我們先前的問題已得到解決。 但是現在,可讀性已經成為一個問題,我想知道是否有一種方法可以重寫此函數,使其更易於閱讀(可能具有較少的代碼),但功能卻相同。
這是它的一個組成部分,為清晰起見,添加了一些注釋,盡管看起來並非如此:
function interval(func, wait, times) {
// Set `t` to either Infinity or the number of times we're supposed to repeat
var t = typeof times == "undefined" ? Infinity : times;
// The tick function we call
function tick() {
// Set up the next iteration if appropriate
// Note that --Infinity is Infinity, so it will never stop in that case
if (--t > 0) {
setTimeout(tick, wait);
}
// Call the function, canceling further repeats if it throws an exception
try {
func.call(null); // Or just func() seems like it should be good enough, really
} catch(e) {
t = 0;
throw e;
}
}
// Start the process
setTimeout(tick, wait);
}
這保留了當前函數的一些行為,這些行為與標准setInterval
不同(我不能說Angular的行為):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.