Change setInterval value dynamically

后端 未结 3 1380
心在旅途
心在旅途 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条回答
  •  無奈伤痛
    2021-02-04 11:37

    The trick is to not use setInterval, and to use setTimeout in a loop instead.

    setInterval reads the timing value you give it once, schedules based on this timing, and forgets about it. The only thing you can do is clearInterval(myInterval) if you've assigned your interval to a variable like myInterval.

    setTimeout is much the same, except we can use it to manually loop on the same function. Manually looping allows us to change the timing of setTimeout after each timeout.

    Here's a quick example. Moving the slider to the left makes the ticking faster, and to the right, slower.

    DEMO

    var timing = 250,
        i = 0,
        output = document.getElementById('output');
    
    function loop() {
      i++;
      output.innerHTML = i;
      window.setTimeout(loop, timing);
    }
    
    document.querySelector('input[type="range"]').addEventListener('change', function (e) {
      timing = parseInt(this.value);
    });
    
    loop();
    
    

    As a side note: Using this pattern is almost always a better option than using setInterval. setInterval runs the chance that your function execution could take longer than the duration of the interval. This never happens with a looping setTimeout if you call setTimeout last in the function.

    Documentation:

    • WindowTimers.setInterval
    • WindowTimers.setTimeout

提交回复
热议问题