Tum Tum - 9 months ago 15
Javascript Question

How to loop through an array in waiting a time between each item?

Ok, 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>

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.

I think we need to do with
or something like that but it is too hard for me to think of it. Maybe a nested setInterval??

So Given an 2-D array of text & millisecond-number, How to print each item out after a specified milliseconds?

Note: I need tp print out in the right order of
, that is it will print out text1 first, then text2, then text3, ...



Finally found the solution

var items = [["text1", 3000],["text2",4000],["text3",1000]];

var time=0;

function printElems(i){
            var elem=document.getElementById("d");
<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.