-->

JavaScript调用函数10之间1秒倍(javascript Call function 10

2019-10-19 07:37发布

如何调用函数的10倍像

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

但与每个呼叫之间1秒?

Answer 1:

您可以使用的setInterval与间隔重复执行,然后clearInterval后10个调用:

callfunction();
var callCount = 1;
var repeater = setInterval(function () {
  if (callCount < 10) {
    callfunction();
    callCount += 1;
  } else {
    clearInterval(repeater);
  }
}, 1000);

补充:但是,如果你不知道需要多长时间你的callfunction执行和调用开始点之间准确的定时并不重要,现在看来,这是更好地使用的setTimeout并通过保罗小号提到的原因那些描述这篇文章 。



Answer 2:

function callNTimes(func, num, delay) {
    if (!num) return;
    func();
    setTimeout(function() { callNTimes(func, num - 1, delay); }, delay);
}
callNTimes(callfunction, 10, 1000);

编辑:该功能基本上是说:使传递函数的调用,然后一点后,再9次做到这一点。



Answer 3:

另一种解决方案

for(var x=0; x<10; x++) window.setTimeout(callfunction, 1000 * x);


Answer 4:

你可以尝试使用setInterval和使用一个变量数到10,试试这个:

var number = 1;
function oneSecond () {
  if(number <= 10) {
    // execute code here..
    number++;
  }
};

现在使用setInterval:

setInterval(oneSecond, 1000);


Answer 5:

类似Amadan的答案 ,但有不同的风格封闭的,这意味着你重新使用,而不是创建新功能

function call(fn, /* ms */ every, /* int */ times) {
    var repeater = function () {
        fn();
        if (--times) window.setTimeout(repeater, every);
    };
    repeater(); // start loop
}
// use it
var i = 0;
call(function () {console.log(++i);}, 1e3, 10); // 1e3 is 1 second
// 1 to 10 gets logged over 10 seconds

在这个例子中,如果你设置times要么0Infinity ,它会永远运行下去。



Answer 6:

我不知道是否有一个合适的名字,但我使用一个中继器:

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);
}

然后,您可以使用它像这样:

new Repeater(callfunction, 1000, 10); // 1 second delay, 10 times


Answer 7:

setInterval(function(){},1000);

要求每一秒的功能...

您还可以使用的setTimeout为你的东西的工作。



文章来源: javascript Call function 10 times with 1 second between