Changing the interval of SetInterval while it's running

后端 未结 16 1405
南旧
南旧 2020-11-22 07:35

I have written a javascript function that uses setInterval to manipulate a string every tenth of a second for a certain number of iterations.

function timer(         


        
16条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 07:55

    A much simpler way would be to have an if statement in the refreshed function and a control to execute your command at regular time intervals . In the following example, I run an alert every 2 seconds and the interval (intrv) can be changed dynamically...

    var i=1;
    var intrv=2; // << control this variable
    
    var refreshId = setInterval(function() {
      if(!(i%intrv)) {
        alert('run!');
      }
      i++;
    }, 1000);
    

提交回复
热议问题