Changing the interval of SetInterval while it's running

后端 未结 16 1046
南旧
南旧 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 08:12

    I like this question - inspired a little timer object in me:

    window.setVariableInterval = function(callbackFunc, timing) {
      var variableInterval = {
        interval: timing,
        callback: callbackFunc,
        stopped: false,
        runLoop: function() {
          if (variableInterval.stopped) return;
          var result = variableInterval.callback.call(variableInterval);
          if (typeof result == 'number')
          {
            if (result === 0) return;
            variableInterval.interval = result;
          }
          variableInterval.loop();
        },
        stop: function() {
          this.stopped = true;
          window.clearTimeout(this.timeout);
        },
        start: function() {
          this.stopped = false;
          return this.loop();
        },
        loop: function() {
          this.timeout = window.setTimeout(this.runLoop, this.interval);
          return this;
        }
      };
    
      return variableInterval.start();
    };
    

    Example use

    var vi = setVariableInterval(function() {
      // this is the variableInterval - so we can change/get the interval here:
      var interval = this.interval;
    
      // print it for the hell of it
      console.log(interval);
    
      // we can stop ourselves.
      if (interval>4000) this.stop();
    
      // we could return a new interval after doing something
      return interval + 100;
    }, 100);  
    
    // we can change the interval down here too
    setTimeout(function() {
      vi.interval = 3500;
    }, 1000);
    
    // or tell it to start back up in a minute
    setTimeout(function() {
      vi.interval = 100;
      vi.start();
    }, 60000);
    

提交回复
热议问题