JS: setInterval and clearIntervals with jQuery

JS: setInterval and clearIntervals with jQuery

本文关键字:with jQuery clearIntervals and setInterval JS      更新时间:2023-09-26

我可能盯着这个看太久了,也许有人能帮我澄清一下:

//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服务器。

clearInterval不接受函数作为参数,它接受setInterval返回的ID。

var theID = setInterval(something,1000);
clearInterval(theID);

James Montagne是对的,但我想我应该使用您提供的代码:

// 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;
    }
}())

正如James Montagne在上面回答的那样,clearIntervalsetInterval函数返回的id。请在mozilla开发人员网络上查看这个示例。

James Montagne的答案是正确的。然而,如果你不想存储setInterval返回的ID,你可以使用jQuery定时器插件

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