2012-01-14 72 views
4

有沒有辦法檢查clearTimeout是否成功。明確超時成功?

我有一個JavaScript函數,它以30秒的間隔異步運行。它是一個自我調用函數,它使用setTimeout()在循環中重複它自己。在特定情況下,我需要在發生某些事件後調用此函數。因此,我首先clearTimeout並再次調用該函數。但是我不知道我是否能夠成功地清除之前的循環,或者現在是否已經開始了兩個獨立的循環。我可以做這樣的事嗎? :

if(clearTimeout(timer)) 
alert("cleared"); 
+1

如果您傳遞了正確的參數,則清除了循環。但是如果你想感到更安全,考慮將另一個參數傳遞給「true」或「false」的函數。如果「false」,該函數不應該設置循環。 – Jon 2012-01-14 04:10:49

+0

我覺得好像應該有一個很好的方式來跟蹤你的計時器的狀態,並始終確信你的clearTimeout是成功的。這是一個簡單的小提琴讓人們開始。 http://jsfiddle.net/ASYgU/ – mrtsherman 2012-01-14 04:37:31

+0

@mrtsherman嗯,我試着弄了一下代碼;輸出可變定時器的值。原來,這是一些增加的數字。有一點是肯定的:'if(timer)'語句總是返回true,不能用來檢查定時器是否在運行。但它可以用來追蹤循環運行的次數。 [更新的小提琴](http://jsfiddle.net/roopunk/ASYgU/4/) – roopunk 2012-01-15 10:36:36

回答

4

「有沒有一種方法來檢查clearTimeout的成功。」

沒有,有沒有保持狀態,您可以查看,但如果你正確地管理你的計時器,它不應該是一個問題。


你可以創建自己的狀態計時器對象,我想......

var _slice = Array.prototype.slice; 

    // substitute for setTimeout 
function myTimer(fn,ms) { 
    var args = _slice.call(arguments,2), 
     timer_state = { 
      complete: false, 
      timer: setTimeout(function() { 
       timer_state.complete = true; 
       fn.apply(this, args); 
      }, ms) 
     }; 
    return timer_state; 
}; 

    // substitute for clearTimeout 
function clearMyTimer(timer_obj) { 
    timer_obj.complete = true; 
    clearTimeout(timer_obj.timer); 
}; 

清除定時器的例子......讓它運行的

// create a timer 
var timer = myTimer(function() { 
    console.log('timer is done'); 
}, 1000); 

console.log(timer.complete); // complete? false 

clearMyTimer(timer); // clear it 

console.log(timer.complete); // complete? true 

例...

// create a timer 
var timer = myTimer(function() { 
    console.log('timer is done'); 
}, 1000); 

console.log(timer.complete); // complete? false 

    // check the timer object after it has expired 
setTimeout(function() { 
    console.log(timer.complete); // complete? true 
}, 1500); 

編輯:更新到使this在嚴格模式下一致,並支持傳遞給回調的附加參數。感謝@Saxoier的提示。

+0

如果您在嚴格的環境中運行代碼(''use strict''),並且使用'this'功能。此外在延遲之後傳遞參數 - 參數將被忽略。其他參數可能在HTML 5中被標準化 - 已經在Firefox,Chrome和Opera中實現,但可以在不支持它的環境中輕鬆實現。 [jsFiddle](http://jsfiddle.net/w3p8T/) – Saxoier 2012-01-14 05:59:25

+0

@Saxoier:好點。我更新了。將額外參數直接應用於回調函數而不是'setTimeout',所以參數通常在不受支持的瀏覽器中運行。 – 2012-01-14 14:08:19

1

是的,這是使用閉包的狀態。它非常直接。

要確保你說你是不是一次又一次地調用它,你可以嘗試這樣的事情......

// declare only once, singleton concept using closure 
(function() { 
    var timerReference, 
    timerMethod = function(fn) { 
     fn(); 
     if (timerReference) { 
      window.clearTimeout(timerReference); 
     } 
     timerReference = window.setTimeout(function() { 
      timerMethod(fn); 
     }, 30000); 
    }; 
    window.doTimer = function(fn) { 
     timerMethod(fn); 
    }; 
})(); 

// you can call this as many times as you like 
doTimer(function() { 
    alert('hi'); 
}); 
doTimer(function() { 
    alert('hi again'); 
}); 

在這種情況下,它調用doTimer()會破壞之前,前一個如此您將一直只有一個計時器。

我也可以編寫一個隊列,等待最後一個完成,但這是另一個寫法。