Changing the interval of SetInterval while it's running

后端 未结 16 1043
南旧
南旧 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:11

    Simple answer is you can't update an interval of already created timer. (There is only two functions setInterval/setTimer and clearInterval/clearTimer, so having a timerId you can only deactivate it.) But you can made some workarounds. Take a look at this github repo.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 08:14

    You can use a variable and change the variable instead.

    ````setInterval([the function], [the variable])```

    0 讨论(0)
  • 2020-11-22 08:21

    Make new function:

    // set Time interval
    $("3000,18000").Multitimeout();
    
    jQuery.fn.extend({
        Multitimeout: function () {
            var res = this.selector.split(",");
            $.each(res, function (index, val) { setTimeout(function () { 
                //...Call function
                temp();
            }, val); });
            return true;
        }
    });
    
    function temp()
    {
        alert();
    }
    
    0 讨论(0)
提交回复
热议问题