gpt4 book ai didi

javascript - 依次运行多个 setIntervals

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:48:00 25 4
gpt4 key购买 nike

我正在尝试运行多个 setInterval(),但我在执行此操作的异步方面遇到了问题。

此示例与我要实现的几乎相同:

var labels = ["Bacon", "Beer", "Steak"];
var second, timer;
labels.forEach(function(label){
second = 0;
timer = setInterval(function(){
console.log(label + ' is awesome ' + second);
if(second === 10) {
clearInterval(timer);
}
second++;
}, 1000);
});

由于 setInterval 是异步的,所以三个间隔并行运行并且弄乱了间隔:

Bacon is awesome 0

Beer is awesome 1

Steak is awesome 2

Beer is awesome 3

Bacon is awesome 4

Steak is awesome 5

Bacon is awesome 6

Beer is awesome 7

Steak is awesome 8

Bacon is awesome 9

Beer is awesome 10

Beer is awesome 11

Bacon is awesome 12

Beer is awesome 13

Bacon is awesome 14

Bacon is awesome 15

Beer is awesome 16

Beer is awesome 17

Bacon is awesome 18

Bacon is awesome 19

Beer is awesome 20

Beer is awesome 21

Bacon is awesome 22

Bacon is awesome 23

...

我想知道如何强制执行某种队列,以便第一个间隔正常运行,然后在 10 秒后执行下一个 setInterval?

我已经快速尝试了 async.js库,但我找不到合适的控制流程。

最佳答案

我做了一个名为“callQueue”的小函数,它调用一个充满函数的数组,按顺序调用一定次数,函数之间有一定的间隔

用法

第一个参数是函数数组,第二个参数是它们应该被调用的次数,第三个是调用之间的时间。

callQueue([

function () {
isAwesome('bacon');
},

function () {
isAwesome('beer');
},

function () {
isAwesome('steak');
}], 10, 1000);

函数

function callQueue(queue, times, timeBetween) {
var i = 0;
k = 0;
queue.forEach(function (func) {
for (k = 0; k < times; k += 1) {
alert(i * timeBetween);
i += 1;
setTimeout(func, (i * timeBetween));
}
});
};

演示:http://jsfiddle.net/howderek/L5nhU/

关于javascript - 依次运行多个 setIntervals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22412545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com