我如何解析一个数组与延迟和修改它,而它是通过循环?



我需要一个函数,可以在考虑延迟的情况下循环遍历数组,而不是在遍历数组时一次性添加延迟。

我需要的例子:

const array = [ 0.06, 0.08, 0.04, 0.05, 0.06, 0.03 ];
loop(array); // this is the function
userInputForStop(); // my function where something causes the array to be deleted/set to []

我试过:

const array = [ ""var array = [ "this", "is", "not", "going", "to", "work" ];
for (var i = 0; i < array.length; i++) {
(function (i) {
setTimeout(function () {
if(i == "going") array = [];
console.log(array[i])
}, 1000 * i);
})(i);
};

这个方法将不起作用,因为for循环已经遍历了每个项目,并且已经设置了超时。因此,当条目匹配"going"时,它不会阻止后面的内容。

我看过很多其他关于数组延迟的帖子,尽管它们似乎都解析数组中的所有项并将延迟乘以计数器(这不是我想要的)。

我想要一个循环函数,允许我完全停止某个项目后的任何值循环。(但每个值之间也有延迟)

我们可以尝试在JavaScript中使用promises重新创建某种睡眠函数。然后我们可以在循环中使用sleep函数,因为循环尊重await:

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const array = ["this", "is", "definitely", "going", "to", "work"];
(async () => {
for (const item of array) {
if (item === "going") array.length = 0;
console.log(item);
await delay(100);
}
})();

,如果你编写一个使用这个sleep函数的异步生成器,我们可以用for-await循环来简化核心循环:

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const array = ["this", "is", "definitely", "going", "to", "work"];
async function* delayedIterator(array, ms) {
for (const item of array) {
yield item;

await delay(ms);
}
}
(async () => {
for await (const item of delayedIterator(array, 100)) {
if (item === "going") array.length = 0;

console.log(item);
}
})();

很难理解你的用例是什么(这将大有帮助),但你可以清除未来的计时器:

const timers = []
const array = [ ""var array = [ "this", "is", "not", "going", "to", "work" ];
for (var i = 0; i < array.length; i++) {
(function (i) {
timers.push(setTimeout(function () {
if(array[i] == "going") {
for (var j = i + 1; i < timers.length; j++) {
clearTimeout(timers[j])
}
array = [];

}
console.log(array[i])
}, 1000 * i));
})(i);
};]

最新更新