javascript Call function 10 times with 1 second between

前端 未结 8 1716
花落未央
花落未央 2021-01-24 17:40

How to call a function 10 times like

for(x=0; x<10; x++) callfunction();

but with 1 sec between each call?

相关标签:
8条回答
  • 2021-01-24 18:24

    const functionCounterTimer = (callCount) => {
      if (callCount < 10) {
        setTimeout(() => {
          ++callCount
          console.log("Function Call ", callCount);
          functionCounterTimer(callCount);
        }, 1000);
      }
    }
    
    functionCounterTimer(0);

    The above was my approach to a similar question.

    0 讨论(0)
  • 2021-01-24 18:28

    I don't know if there's a proper name, but I use a repeater:

    function Repeater(callback, delay, count) {
        var self = this;
        this.timer = setTimeout(function() {self.run();},delay);
        this.callback = callback;
        this.delay = delay;
        this.timesLeft = count;
        this.lastCalled = new Date().getTime();
    }
    Repeater.prototype.run = function() {
        var self = this;
        this.timesLeft--;
        this.callback();
        this.lastCalled = new Date().getTime();
        if( this.timesLeft > 0) {
            this.timer = setTimeout(function() {self.run();},this.delay);
        }
    }
    Repeater.prototype.changeDelay = function(newdelay) {
        var self = this;
        clearTimeout(this.timer);
        this.timer = setTimeout(function() {self.run();},
                              newdelay-new Date().getTime()+lastcalled);
        this.delay = newdelay;
    }
    Repeater.prototype.changeCount = function(newcount) {
        var self = this;
        if( this.timesLeft == 0) {
            this.timer = setTimeout(function() {self.run();},this.delay);
        }
        this.timesLeft = newcount;
        if( this.timesLeft == 0) clearTimeout(this.timer);
    }
    

    You can then use it like this:

    new Repeater(callfunction, 1000, 10); // 1 second delay, 10 times
    
    0 讨论(0)
提交回复
热议问题