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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16599878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:26:47  来源:igfitidea点击:

Can clearInterval() be called inside setInterval()?

javascriptjquerysetintervalclearinterval

提问by yvonnezoe

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

I have the code above and sometimes it is working, sometimes it is not. I am wondering if the clearInterval actually clear the timer??because there is this monitorbutton that will only be disabled when it is in monitoringfunction. I have another clearIntervalwhen an element called .outputRemoveis clicked. See the code below:

我有上面的代码,有时有效,有时无效。我想知道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;

            });
        });

But it was enabled for a while before it is disabled again. Will clearIntervalget the program out from the setIntervalfunction?

但是它在再次禁用之前启用了一段时间。clearIntervalsetInterval函数中取出程序吗?

回答by Joseph

Yes you can. You can even test it:

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

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

In this example, this timer clears when ireaches 5.

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