2011-11-24 35 views
0

我可能在這盯着太久累了, 也許有人可以清除此爲我:JS:的setInterval和clearIntervals與jQuery

//scripts in whispers are setup this way. 
var something = function(){ 
    setInterval(function1,1000); 
    setInterval(function2,1000); 
    blah .. blah... 
} 

//function2 is the same as this one 
var function1 = function(){ 
    ajax to do something on server 
    blah... 
    blah... 
} 

//button to stop things from running anymore 
$('.stop').live('click',function(){ 
    clearInterval(function1); 
    clearInterval(function2); 
    return false; 
} 

我應該能夠停止功能1和/或2運行後 點擊按鈕是啊?出於某種原因 - 在 兩個函數內的ajax調用繼續運行並ping服務器。

回答

4

clearInterval不作爲參數使用函數,它需要返回setInterval的ID。

var theID = setInterval(something,1000); 

clearInterval(theID); 
+0

感謝詹姆斯! 感謝JesseB的例子(下圖):http://stackoverflow.com/q/8251941/294895 – kenok

0

正如詹姆斯蒙塔涅上面已經回答,clearInterval採用由setInterval函數返回的ID。請在mozilla開發人員網絡上提供此example

+1

將鏈接發佈爲評論而不是重複答案會更有意義嗎? –

1

詹姆斯·蒙塔涅是正確的,但我想我會使用您所提供的是什麼符號UP:

// declaring this as a closure, so 
// that your timers are kept out of the global namespace 
(function(){ 
    var timer1, 
     timer2; 

    // declaring 'something' this way makes it private 
    // use this.something if you want to be able to access this publicly 
    var something = function(){ 
     timer1 = setInterval(function1, 1000); 
     timer2 = setInterval(function2, 1000); 
     // blah .. blah... 
    } 

    //function2 is the same as this one 
    var function1 = function(){ 
     // ajax to do something on server 
     // blah... 
     // blah... 
    } 

    // button to stop things from running anymore 
    $('.stop').on('click', function(e) { 
     // kill out our timers 
     clearInterval(timer1); 
     clearInterval(timer2); 

     // prevent the browsers default click action 
     if (e.preventDefault) { 
      e.preventDefault(); 
     } 
     return false; 
    } 
}()) 
0

詹姆斯·蒙塔涅的答案是正確的。但是,如果你不想存儲由setInterval返回的ID,你可以使用jQuery timers插件

$(window).everyTime(1000, "task1", function1); //set interval 
$(window).stopTime("task1");      //clear interval