Stop setInterval call in JavaScript

前端 未结 16 1801
星月不相逢
星月不相逢 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:48

    Declare variable to assign value returned from setInterval(...) and pass the assigned variable to clearInterval();

    e.g.

    var timer, intervalInSec = 2;
    
    timer = setInterval(func, intervalInSec*1000, 30 ); // third parameter is argument to called function 'func'
    
    function func(param){
       console.log(param);
    }
    

    // Anywhere you've access to timer declared above call clearInterval

    $('.htmlelement').click( function(){  // any event you want
    
           clearInterval(timer);// Stops or does the work
    });
    

提交回复
热议问题