function test(counter) { if(counter==4) { counter=0; } if(c...">

Jquery - how to stop a function?

I have this code

<script type="text/javascript"> 
  function test(counter) {
      if(counter==4)
        {
              counter=0;
         }
      if(counter==0)
         {
            //various stuff

          }

          counter = counter + 1;
         setTimeout(function () { test(counter); }, 7000);
  }

 $(document).ready(function () {

 test(0);

 });
 </script>

So, when the page loads the function test(0).

But I have this link <a onclick="test(1)" rel="2" href="#">that calls the same function again, resulting in the same function being executed twice.

Is there a way to stop an already running function and then start a new one.

+3
source share
2 answers

Save the result setTimeout()and use it with clearTimeout().

+4
source
function test(counter) {
      if(counter==4)
        {
              counter=0;
         }
      if(counter==0)
         {
            //various stuff

          }

          counter = counter + 1;



          var quit;
          //decide whether to continue
         if(!quit)setTimeout(function () { test(counter); }, 7000);


  }
0
source

All Articles