Change setInterval value dynamically

后端 未结 3 1341
心在旅途
心在旅途 2021-02-04 11:01

I want to change interval value of setInterval dynamically. I\'m struggling due to presence of a loop in setInterval callback function. I have seen too many questions on stackov

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 11:42

    Here's another easy way to dynamically update interval.

    var intv_sec = 1500; // Initial interval in milliseconds
    var speed = 1.5; // Multiplier
    
    function chk_fn(){
      // Your code here
      console.log(intv_sec);
      
      
      // Reset and update interval
      clearInterval(chkh);
      intv_sec = intv_sec*speed;
      chkh = setInterval(chk_fn, intv_sec);
    }
    
    var chkh = setInterval(chk_fn, intv_sec);

提交回复
热议问题