问题描述
我有一个带有 timestamp
的事件列表.我想要的是根据 timestamp
显示事件:
I have a list of events with timestamp
.What I want is to display the events based on the timestamp
:
添加延迟:
delay = timestamp(t+1) - timstamp(t)
我知道这不适用于 setTimeout
,但是有一个解决方法,如果超时是恒定的,在我的情况下不是.
I know this doesn't work well with setTimeout
, but there is an workaround, if the timeout is constant, in my case is not.
是否可以让下一个 setTimeout()
等待上一个?具体来说,如果第一个 setTimeout()
有 5 秒延迟,第二个有 3 秒,则第二个会先出现.我希望它们的顺序相同,但一个接一个执行.
Is it possible to make the next setTimeout()
wait for the previous one? To be specific, if the first setTimeout()
has a 5 second delay and the second one has 3 seconds, the second one will appear first. I want them to be in the same order but execute one after the other.
此示例适用于恒定延迟,但我想根据迭代列表的信息计算延迟.
This example works for a constant delay, but I want to calculate the delay based on the information I take iterating the list.
for (i = 1; i <= 5; ++i) {
setDelay(i);
}
function setDelay(i) {
setTimeout(function(){
console.log(i);
}, 1000);
}
推荐答案
您可以使用 IIFE(立即调用的函数表达式) 和函数递归代替.像这样:
You can use IIFE (Immediately Invoked Function Expression) and function recursion instead. Like this:
let i = 0;
(function repeat(){
if (++i > 5) return;
setTimeout(function(){
console.log("Iteration: " + i);
repeat();
}, 5000);
})();
Live fiddle 这里.
Live fiddle here.
这篇关于具有可变延迟和等待的 Angular 4 setTimeout()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!