我需要帮助创建一个函数,每次以3秒的时间间隔返回数组中的3个元素。 假设我有一个数组
const Array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},{name:'F'},{name:'G'},{name:'H'},{name:'I'}];
它应该返回像
这样的数组 [{name:'A'},{name:'B'},{name:'C'}]
然后在3秒后它应该返回数组
[{name:'D'},{name:'E'},{name:'F'}]
等等,当数组结束时再次重复循环。
我尝试使用chunk,其中我使用了切片和过滤器,但这只是将一组块返回给我。
非常感谢
答案 0 :(得分:2)
您可以使用生成器执行此操作:
// Takes an array and the of the slice/subarray
function* subArray(array, size) {
let i = 0;
let remaining = true;
while (remaining) {
yield array.slice(i, i + size);
i += size;
if (i >= array.length) {
remaining = false;
}
}
}
// Takes an array, a subarray size, and an interval in seconds
const getSubArraysAtInterval = (array, size, seconds) => {
const iter = subArray(array, size);
const interval = setInterval(() => {
const next = iter.next();
if (next.done) {
clearInterval(interval);
console.log('No values remaining');
} else {
console.log(next.value);
}
}, seconds * 1000)
}
getSubArraysAtInterval([1, 2, 3, 4, 5, 6], 3, 3);
答案 1 :(得分:1)
const array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},
{name:'F'},{name:'G'},{name:'H'},{name:'I'}];
let i = 0
setInterval(() => {
console.log(array.slice(i,i+3))
i*3 > array.length ? i=0 : i += 3
}, 3000)