JS:使用jQuery的setInterval和clearIntervals

时间:2011-11-24 02:46:45

标签: javascript 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;
}

我应该能够停止运行后的function1和/或2 点击按钮是啊?由于某种原因 - ajax调用 两个函数继续运行并ping服务器。

4 个答案:

答案 0 :(得分:4)

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

var theID = setInterval(something,1000);

clearInterval(theID);

答案 1 :(得分:1)

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

答案 2 :(得分:0)

正如James Montagne上面回答的那样,clearInterval获取了setInterval函数返回的id。请在mozilla开发者网络上查看此example

答案 3 :(得分:0)

James Montagne的回答是正确的。但是,如果您不想存储setInterval返回的ID,则可以使用jQuery timers插件

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