如何使用Jquery停止setInterval Timer

时间:2014-05-12 08:10:51

标签: javascript jquery

我使用带有jquery的setInterval()每隔2秒从网络摄像头加载和刷新图片,如下例所示:

$("cameralist").change(function(){
    $("cameralist option:selected").each(function(){
        var timer = setInterval(loadImage(), 2000); 

        function loadImage(){
            $("div.img").attr("src", URL); 
        }
    });
});

我的问题是,我想清除每个更改事件的计时器(每次在列表中选择新的或其他摄像机)并重新启动计时器......

我该怎么做?任何想法?

3 个答案:

答案 0 :(得分:2)

  

如何使用Jquery

停止SetInterval Timer

你没有。但你可以用JavaScript做到这一点:

clearInterval(timer);

但是,您需要将timer变量放在<{1}}处理程序之外。我最初也将它设置为change(使用0调用clearInterval是无操作,因此它是一个方便的初始值。)

另请注意,您没有正确设置间隔。这一行:

0

调用 var timer = setInterval(loadImage(),2000); 并将其返回值传递到loadImage,与setInterval 调用 foo(bar())完全相同它的返回值为bar。要参考该功能,请在foo之后删除()

这些方面的东西:

loadImage

但是,我认为没有理由将图片的// Note: I'm assuming this code isn't at global scope. If it is, wrap it in a // scoping function, we don't want or need `timer` to be global. var timer = 0; // <== Initialize timer variable $("cameralist").change(function () { $("cameralist option:selected").each(function () { clearInterval(timer); // <=== Clear previous timer if any timer = setInterval(loadImage, 2000); // <=== Set new timer // No () here ---------------^ function loadImage() { $("div.img").attr("src", URL); } }); }); 重复设置为同一网址,除非该网址的内容发生变化(并禁用了缓存)。如果内容发生变化,请继续使用src。如果没有,请查看使用setInterval代替(它是一次性计时器,而不是重复计时器)。

答案 1 :(得分:1)

将计时器作为全局变量并不是一个好主意。

/**
 * It is not good idea to have timer
 * as s global variable.
 */

$("cameralist").change((function (timer) {
    return function () {
        if (timer != null) {
            clearInterval(timer);
        }
        $("cameralist option:selected").each(function () {
            timer = setInterval(loadImage, 2000);
            function loadImage() {
                $("div.img").attr("src", URL);
            }
        });
    }
})(null));

答案 2 :(得分:0)

没有jquery需要,可以使用原始javascript

clearInterval(timer)

像这样使用

$("cameralist").data().timer = null;

$("cameralist").change(function(){


  $("cameralist option:selected").each(function(){

       clearInterval($("cameralist").data().timer);
       $("cameralist").data().timer = setInterval(loadImage(),2000); 

       function loadImage(){

         $("div.img").attr("src", URL); 

       }
  });

});

如果加载定时器清除

像这样使用

$("cameralist").data().timers = [];

$("cameralist").change(function(){
  _.each($("cameralist").data().timers, function(timer) {
      setInterval(timer);
  });
  $("cameralist").data().timers = [];

  $("cameralist option:selected").each(function(){
       var timerRef = setInterval(loadImage(),2000); 
       $("cameralist").data().timers.push(timerRef);

       function loadImage(){

         $("div.img").attr("src", URL); 

       }
  });

});

https://developer.mozilla.org/en-US/docs/Web/API/Window.clearInterval

同样伟大的思想相似:) +1到下面的人

相关问题