d3每次迭代等待n秒



我试图在d3中同步迭代,每次迭代等待特定的秒数。

years = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for (iter = 0; iter <= years.length; iter++) {
setTimeout(function() {
console.log(iter);
}, 5000);
}

我想要的是打印1,然后等待5秒,然后打印2,然后等待五秒钟,然后打印3,等等。

我读到For循环在D3.js中不起作用,D3.js指出,当迭代时,程序将在完成第一次迭代之前进入下一次迭代的console.log语句,因此它将几乎同时执行所有这些语句。

有没有办法打印1、等待5秒、打印2、等待5秒钟、打印3等?

谢谢!

下面的片段显示了使用递归函数实现等待的方法。

您会注意到d3在本例中根本没有使用,就像问题中分享的一样。如果动画需要每5秒执行一次,那么使用d3.timeout而不是setTimeout可能会提供更好的性能。

years = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
function processYear(currentIndex) {
console.log('processing year', years[currentIndex], ' - currentIndex equals', currentIndex)

if (currentIndex < years.length-1) {
// schedule processing of following year in 5 seconds
setTimeout(function() {
processYear(++currentIndex)
}, 5000)
}
}
// process first item of the year array
processYear(0)

promise = (val) => new Promise(res => setTimeout(() => {
console.log(val)
res()
}, 5000));
(async() => {
years = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for (iter = 0; iter <= years.length; iter++) {
await promise(iter);
}
})()

最新更新