Search code examples
javascriptloopstimer

setTimeout in for loop (1 timeout then loop at once) (double loop)


I followed the answer to this post, however, this doesn't seem to work for me. I have a first 2 dimensional array, I want to timeout between every outer loop and not timeout in the outer loop.

Here's a snippet of this Fiddle showing one of the three ways I tried, from the aforementioned question as well as this one (cf. case 1, 2 and 3).

    var data = [
                [
                    ["data[0][0]"],  
                    ["data[0][1]"]
                ],
                [
                    ["data[1][0]"],
                    ["data[1][1]"]
                ],
                [
                    ["data[2][0]"],
                    ["data[2][1]"]
                ]
            ];	

    var delay = 1000;
    
        function doSomething(i) {
    	setTimeout(function() {
      	for(let j = 0; j < data[i].length; j++) {
        console.log(data[i][j]);
        $('#result').html($('#result').html() + data[i][j]);
        }
      }, delay);
    }
    
    for(let i = 0; i < data.length; i++) {
    	doSomething(i);
    }
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <div id="result"></div>

More questions/answers on the subject tend to yield the same result so I am at a loss.


Solution

  • The problem is in how the setTimeout works. It's not a sleep command where it stops the for loop. Rather, it is blazing through the initial for loop, and starting three timers at roughly the same time, to last for one second each. That means they also all end at about the same time.

    You can get your desired outcome by doing something more like this (notice the i*delay for the timer on the setTimeout. That way your first timer is for 0ms, second for 1000ms, third for 2000ms, and you get the staggered results you're after.

    var data = [
      [
        ["data[0][0]"],
        ["data[0][1]"]
      ],
      [
        ["data[1][0]"],
        ["data[1][1]"]
      ],
      [
        ["data[2][0]"],
        ["data[2][1]"]
      ]
    ];
    
    var delay = 1000;
    
    function doSomething(i) {
      setTimeout(function () {
        for (let j = 0; j < data[i].length; j++) {
          console.log(data[i][j]);
          $('#result').html($('#result').html() + data[i][j]);
        }
      }, i*delay);
    }
    
    for (let i = 0; i < data.length; i++) {
      doSomething(i);
    }
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <div id="result"></div>