[英]How to loop through an array in waiting a time between each item?
I have an array like this:我有一个这样的数组:
var items = [["text1", 3000],["text2",4000],["text3",1000]], ...a lot more here...;
. .
In the html side, we got <div id="d"></div>
在 html 端,我们得到
<div id="d"></div>
Now, I want to print out " text1 " on the div after 3000 milliseconds, the PC will then wait for 4000 milliseconds before printing " text2 ", then it will print out " text3 " after 1000 milliseconds, so on until it finishes the loop.现在,我想在 3000 毫秒后在 div 上打印“ text1 ”,然后 PC 将在打印“ text2 ”之前等待 4000 毫秒,然后在 1000 毫秒后打印出“ text3 ”,依此类推,直到完成循环.
I think we need to do with setInterval
or something like that but it is too hard for me to think of it.我认为我们需要使用
setInterval
或类似的东西,但我很难想到它。 Maybe a nested setInterval ??也许是嵌套的setInterval ??
So Given an 2-D array of text & millisecond-number, How to print each item out after a specified milliseconds?那么给定一个二维文本数组和毫秒数,如何在指定的毫秒后打印出每个项目?
Note: I need to print out in the right order of items
, that is it will print out text1 first, then text2, then text3, ...注意:我需要按照
items
的正确顺序打印出来,也就是说它会先打印出 text1,然后是 text2,然后是 text3,...
Edit编辑
Finally found the solution终于找到解决办法
var items = [["text1", 3000],["text2",4000],["text3",1000]]; var time=0; printElems(0); function printElems(i){ setTimeout(function(){ var elem=document.getElementById("d"); elem.innerHTML=items[i][0]; if(items[i+1]!=undefined){ printElems(i+1); } },items[i][1]); }
<div id="d"></div>
This will do the trick.这将解决问题。 What I have done here is, just sum the times and make setTimeout calls based on the delay.This loops through the array in the given order.
我在这里所做的是,将时间相加并根据延迟进行setTimeout调用。这会按给定的顺序循环遍历数组。
Unfortunately, they will be printed from the shortest time to the longest time if you wrap a setTimeout
(asynchronous) in a loop (synchronous).不幸的是,如果将
setTimeout
(异步)包装在循环(同步)中,它们将从最短时间到最长时间打印。
To solve the problem you can use Promises.为了解决这个问题,你可以使用 Promises。
Here is an implementation with jQuery.Deferred :这是jQuery.Deferred的实现:
var dfd = $.Deferred().resolve();
items.forEach((item) => {
dfd = dfd.then(() => print(item));
});
function print(item) {
var dfd = $.Deferred();
setTimeout(() => {
$('#d').html(item[0]);
dfd.resolve();
}, item[1]);
return dfd.promise();
}
With promises, compactly:带着承诺,简洁地:
function wait(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
items.reduce((promise, [text, ms]) =>
promise . then(() => wait(ms)) . then(() => console.log(text)),
Promise.resolve());
With setTimeout
, recursively:使用
setTimeout
,递归地:
function sequence(array) {
if (!array.length) return;
var elt = array.shift();
setTimeout(() => {
console.log(elt[0]);
sequence(array);
}, elt[1]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.