可以在setInterval()中调用clearInterval()吗?

yvo*_*zoe 108 javascript jquery setinterval clearinterval

bigloop=setInterval(function () {
              var checked = $('#status_table tr [id^="monitor_"]:checked');
                if (checked.index()===-1 ||checked.length===0 || ){
                    bigloop=clearInterval(bigloop);
                    $('#monitor').button('enable');
                }else{

                        (function loop(i) {                           
                            //monitor element at index i
                            monitoring($(checked[i]).parents('tr'));
                            //delay of 3 seconds
                            setTimeout(function () {
                                //when incremented i is less than the number of rows, call loop for next index
                                if (++i < checked.length) loop(i);
                            }, 3000);
                        }(0)); //start with 0
                }                            
            }, index*3000); //loop period
Run Code Online (Sandbox Code Playgroud)

我有上面的代码,有时它工作,有时它不是.我想知道clearInterval是否真的清除了计时器?因为有这个monitor按钮只有在它monitoring起作用时才会被禁用.clearInterval.outputRemove点击一个被调用的元素时,我有另一个.请参阅以下代码:

//remove row entry in the table      
        $('#status_table').on('click', '.outputRemove', function () {
            deleted= true;
            bigloop= window.clearInterval(bigloop);
            var thistr=$(this).closest('tr');
            thistr.remove();
            $('#monitor').button('enable');

            $('#status_table tbody tr').find('td:first').text(function(index){
               return ++index;

            });
        });
Run Code Online (Sandbox Code Playgroud)

但是在它再次被禁用之前已经启用了一段时间.clearInterval从程序中获取程序setInterval吗?

Jos*_*eph 175

是的你可以.你甚至可以测试它:

var i = 0;
var timer = setInterval(function() {
  console.log(++i);
  if (i === 5) clearInterval(timer);
  console.log('post-interval'); //this will still run after clearing
}, 200);
Run Code Online (Sandbox Code Playgroud)

在此示例中,此计时器在i达到5 时清除.

  • 这种方法有效的事实令我难以置信。我们在变量定义本身中引用变量。如果我们仍在定义“计时器”是什么,然后将其作为clearInterval 的参数调用,那么这是如何工作的? (11认同)
  • 我知道了.它必须始终是局部变量吗?在我的情况下,我将它设置为全局因为我有外部函数将调用clearInterval ...而且,我当时有2个setInterval并且它们发生冲突:/ (4认同)
  • 答案很好,但是这个评论“//这将在清除后仍然运行”是不明确的,正确的评论是:“//这仅运行一次并停止” (4认同)
  • 如果您知道[事件循环如何工作](https://www.youtube.com/watch?v=8aGhZQkoFbQ),@TeeJ 计时器、ajax 和其他异步操作等将开始有意义。在这种情况下,“setInterval”只是将计时器 ID 返回给“timer”。当_至少_ 200ms过去后,回调被调用。到那时,你_do_就有了一个带有值的“timer”变量。 (3认同)