DrStrangeLove
DrStrangeLove

Reputation: 11557

How do i set one second delay between iterations?

var arr = [[1,2,3],[4,5,6],[7,8,9]];


function out(ar){

  var interval = setInterval(function(){
    for (var i=0; i<ar.length;i++){

      for (var j=0;j<ar[i].length;j++){

        document.write(ar[i][j]);

      }
    document.write("</br>");
    }
  clearInterval(interval);
  },1000);

}

out(arr);

http://jsbin.com/edanib/edit

This code works, but i would like to make one second delay before outputting every number. The above code cannot do that. How do i do that in vanilla Javascript?

Upvotes: 0

Views: 700

Answers (3)

Mike Samuel
Mike Samuel

Reputation: 120516

setInterval isn't guaranteed to get you 1 second spacing because other things might run, but you can get close with the following

function out(ar) {
  var i = 0, j = 0;
  var interval = setInterval(function(){
    // Start with the next row if the last one was finished.
    if (i < ar.length && j == ar[i].length) {
      ++i; 
      j = 0;
      // Put a line after it.
      document.body.appendChild(document.createElement('br'));
    }
    // Check if we're out of rows.
    if (i >= ar.length) { clearInterval(interval); return; }

    // Write out a number.
    document.body.appendChild(document.createTextNode('' + ar[i][j]));

    // We're done with the cell that we just wrote.
    ++j;
  }, 1000 /* milliseconds */);
}

Put the array indices outside the function, so each time the interval fires, it gets the loop state from the last run.

Also, you can't use document.write inside an interval handler because calling document.write after the document has closed clobbers the existing document.

Upvotes: 1

JaredPar
JaredPar

Reputation: 754763

The easiest way to do this is to create a loop with setInterval. Have the function capture the counters and increment them appropriate at every turn

Try the following

function output(arr) {
  var i = 0; 
  var j = 0;
  var interval = setInterval(function () { 

    while (i < arr.length && j === arr[i].length) {
      j = 0;
      i++;
    }

    if (i === arr.length) {
      clearInterval(interval);
    } else {
      document.write(arr[i][j]);
    }
    j++;
  }, 1000);
};

Upvotes: 0

Alex Schenkel
Alex Schenkel

Reputation: 832

try it like this: first, create a single-dimension array, which you give to an output function that calls itself delayed:

var arr = [[1,2,3],[4,5,6],[7,8,9]];


function out(ar){
    var singleDim = []
    for (var i=0; i<ar.length;i++){

      for (var j=0;j<ar[i].length;j++){

          singleDim.push(ar[i][j]);

      }
    }
    outDelayed(singleDim,0,1000);
}

function outDelayed(arr,index,delay) {
    if (index < arr.length) {
        document.write(arr[index]);
        setTimeout(function(){
            outDelay(arr,index+1,delay);
        },delay);
    }
}

out(arr);

Upvotes: 0

Related Questions