2011-04-07 51 views
0

用setInterval()函數執行幾次函數的最佳方法是什麼? 與是我在這裏的嘗試,即清空間隔當變量「計時器」不知道這個問題...使用setInterval()讓函數運行多次的最佳方法是什麼?

... 
     if (counter.hasClass("superWarn")){ 
      var timer = setInterval(toggleCharCount(), 500); 
    } 
... 

function toggleCharCount() { 
    if(typeof toggleCharCount.i == 'undefined'){ 
     toggleCharCount.i = 0; 
    } 
    toggleCharCount.i++; 
    $('#twCharCount').toggle(); 
    if (toggleCharCount.i>=4){ 
     window.clearInterval(timer); 
     toggleCharCount.i = 0; 
    } 
} 

THX的任何意見...

+0

在for循環中如何? – acconrad 2011-04-07 19:22:10

+0

你是否在另一個函數中定義了定時器? – Headshota 2011-04-07 19:24:54

回答

3

爲什麼不ü通過計時器進入回電話?

... 
     if (counter.hasClass("superWarn")){ 
      var timer = setInterval(function(){toggleCharCount(timer)}, 500) 
    } 
... 

function toggleCharCount(timer) { 
    if(typeof toggleCharCount.i == 'undefined'){ 
     toggleCharCount.i = 0; 
    } 
    toggleCharCount.i++; 
    $('#twCharCount').toggle(); 
    if (toggleCharCount.i>=4){ 
     window.clearInterval(timer); 
     toggleCharCount.i = 0; 
    } 
} 
+0

這應該是像'setInterval(function(){toggleCharCount(timer)},500)''。 – Chuck 2011-04-07 19:36:44

+0

@Chuck固定,謝謝 – Neal 2011-04-07 19:37:33

1

我看不到你的完整的JavaScript代碼,看起來變量計時器不在全局範圍內。如果將'timer'移動到globalscope中,函數'toglleCharCount()'將獲得訪問權限。

+0

是的,但我不想爲此設置一個全局... – haemse 2011-04-07 19:28:17

0

1)從我的測試中,如果您命名一個函數作爲一個變量,它不能很好:d:

var foo = {i:'my number'}; 
function foo(){ 
    alert(foo.i); 
} 

要麼foo將被解釋作爲一個對象,或者作爲一個函數,但它不能同時擁有兩個不同的值。
2)當您發送參數作爲函數調用(setTimeout(myFunction(),t))時,函數在定義setTimeout時執行。做正確的方法是發送一個函數,而不是一個函數調用,或將被評估的字符串:

setTimeout(myFunction,t); 
// or 
setTimeout("myFcuntion()",t); 
// or the best way : 
setTimeout(function(){myFunction();},t); 

3)timer在不同範圍內聲明比clearInterval功能,故當您要清除間隔,您沒有任何參考間隔本身,因爲timerundefined。您應該在相同範圍內對它們進行刪除修改,或者您可以將timer設爲全局(沒有var關鍵字),從而在全局範圍內顯示timer,其他任何3d方都可以看到它。

相關問題