Stop setInterval call in JavaScript

前端 未结 16 1803
星月不相逢
星月不相逢 2020-11-21 05:00

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?

I want the us

16条回答
  •  孤街浪徒
    2020-11-21 05:47

    You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:

    var intervalId = null;
    var varCounter = 0;
    var varName = function(){
         if(varCounter <= 10) {
              varCounter++;
              /* your code goes here */
         } else {
              clearInterval(intervalId);
         }
    };
    
    $(document).ready(function(){
         intervalId = setInterval(varName, 10000);
    });
    

    I hope that it helps and it is right.

提交回复
热议问题