9

i have a setInterval() function which is used as follows

        setInterval(function(){

           if(window.document.drops.isFinished()){
               //I want to exit the setInterval() on executing this if
           }

        },1000);

or tell me what is the method to exit.(In java we use System.exit(0))

nicosantangelo
  • 13,216
  • 3
  • 33
  • 47
Udanesh N
  • 161
  • 2
  • 2
  • 15
  • 4
    possible duplicate of [Stop setInterval call in javascript](http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – JJJ Jul 06 '13 at 18:32
  • @juhana is it the same?? i want to exit the setInterval() from inside ,on executing the if condition unless it should continue – Udanesh N Jul 06 '13 at 18:36
  • Yes, it is the same. Unless you're talking about exiting the function in that particular case, when you can just use `return`. – JJJ Jul 06 '13 at 18:36
  • You mean i have to call the clearInterval() from inside the if is it? – Udanesh N Jul 06 '13 at 18:40
  • Yes, just like Nico's answer shows. – JJJ Jul 06 '13 at 18:40
  • It's funny how the duplicates always appear higher in google search than the original questions. – JohnMerlino Apr 23 '14 at 21:09
  • Possible duplicate of [How to exit from setInterval](http://stackoverflow.com/questions/1795100/how-to-exit-from-setinterval) – Pardeep Jain Oct 15 '16 at 10:38

1 Answers1

23
    var timerId = setInterval(function(){

       if(window.document.drops.isFinished()){
           clearInterval(timerId);
       }

    },1000);

If the if it's not the last thing in the function and you want to "break" the execution, maybe you want to also add a return; statement after the clearInterval.

nicosantangelo
  • 13,216
  • 3
  • 33
  • 47
  • 5
    +1. Might be a good idea to add a `return` after the `clearInterval` call too (in case there's other stuff after the `if`). – Cameron Jul 06 '13 at 18:36