216
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 monitor button that will only be disabled when it is in monitoring function. I have another clearInterval when an element called .outputRemove is clicked. See the code below:

//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 clearInterval get the program out from the setInterval function?

yvonnezoe
  • 7,129
  • 8
  • 30
  • 47
  • Maybe the problem is `loopname` in the second snippet? What is that? – bfavaretto May 17 '13 at 01:11
  • opps typo. i had a function `clearloop(loopname)` which contains the `clearInterval` but to simplify it, i changed it directly in the code above. – yvonnezoe May 17 '13 at 01:13

1 Answers1

377

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'); // interval will be cleared after completing this whole block
}, 200);

In this example, this timer clears when i reaches 5.

Pushkin
  • 3,336
  • 1
  • 17
  • 30
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 6
    i see. must it always be a local variable? in my case, i set it as global because i have outer function that will call clearInterval... and also, i have 2 setInterval at the time being and they are clashing :/ – yvonnezoe May 17 '13 at 01:15
  • i have a question here, will it stuck at the point of `clearInterval` if the `setInterval` has stopped somewhere else / hasnt start at all? – yvonnezoe May 17 '13 at 01:21
  • @yvonnezoe updated the answer, and that's no. The function that runs per interval finishes before it's never run again. However, on the case of your question, you've got multiple timers. I suggest you rethink your approach. – Joseph May 17 '13 at 01:25
  • Okay thank you for clarifying! :) then it must be some logic errors in my program. – yvonnezoe May 17 '13 at 01:31
  • Hijoseph, The statement executing its part of your function, which calling by your timer after defined interval. So, when you clearing your interval by calling clearInterval(timer), it is absolute that timer has been already cleared, but the following statement, console.log('post-interval'); //this will still run after clearing, of function(), has to executed. – irejwanul Dec 07 '16 at 11:11
  • 10
    The fact that this approach works boggles my mind. We are referencing a variable in the variable definition itself. How does this work if we are still defining what 'timer' is and then calling it as an argument to clearInterval? –  Oct 25 '19 at 13:26
  • 1
    @TeeJ Timers, ajax, and other async operations, etc. will start to make sense if you know [how the event loop works](https://www.youtube.com/watch?v=8aGhZQkoFbQ). In this case, `setInterval` simply returns a timer id to `timer`. When _at least_ 200ms has passed, the callback is called. By that time, you _do_ have a `timer` variable with a value. – Joseph Oct 25 '19 at 13:37
  • Thanks @Joseph That makes sense and the video helped alot. The function inside setInterval was just a callback that gets pushed to a task queue. So by the time that callback is executed it has a reference to the 'timer' id? –  Oct 25 '19 at 14:13
  • I would not call the variable `timer`,but rather `id`. JS is a crazy language because in other (compiled) languages as @user.. points out, you cannot reference a local variable from outside inside a function. – Timo Jun 03 '20 at 07:58
  • 8
    The answer is good but this comment `//this will still run after clearing` is ambiguous the correct comment would be : `//This run ONLY ONE TIME and stop` – MTK Aug 24 '20 at 13:52
  • Does is it possible reference with this instead of the name of variable ? – cicciosgamino Jul 07 '21 at 08:27
  • @MTK the comment is not ambiguous, the timer STILL RUNS on every interval difference. I have no idea where you got the only once idea from. – Artexias Jan 06 '23 at 08:52
  • @Artexias Possibly it is due to my little knowledge of the English language. To my understanding, `still run`, means it does not stop. `still run` vs `run once` or `one-off` or `one more` – MTK Jan 06 '23 at 12:44