2011-11-24 71 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