Question

Completely stuck.

I have seen this popular solution for adding delays between iterations of a loop (https://stackoverflow.com/a/3583740), but it only seems to work for a single loop (i.e not nested).

This is the pseudo code,

for (var i = 0; i < max; i++){
    for (var j = 0; j < max; j++){  
        pause(1000);         // ideally would just elegantly pause all execution
    }
}

I am trying to use setTimeout (unless other options exist!) but I can't seem to wrap my head around how to set it up.


Context - It should pause long enough for an animation to occur. (A different animation occurs depending on the values of i and j ).

Was it helpful?

Solution

As it has been said, you can't really pause execution in javascript. Though a trick could be to collect the instructions in a delayed queue which executes itself fifo. E.g.:

// helper function
var delayed = (function() {
  var queue = [];

  function processQueue() {
    if (queue.length > 0) {
      setTimeout(function () {
        queue.shift().cb();
        processQueue();
      }, queue[0].delay);
    }
  }

  return function delayed(delay, cb) {
    queue.push({ delay: delay, cb: cb });

    if (queue.length === 1) {
      processQueue();
    }
  };
}());

your example, rewritten:

var i = 0, j, max = 3;

for (; i < max; i += 1) {
  for (j = 0; j < max; j += 1) {
    // add function to the queue, shadowing i/j with an IIFE:
    delayed(1000, function(i, j) {
      return function() {
        console.log(i, j);
      };
    }(i, j));
  }
}

demo: http://jsbin.com/kadepage/1/

OTHER TIPS

This will work as nested for loop with delay.

    var i = o = 0;
    var max = 10;
    var delay = 1000;
    function rec()
    {   
        console.log("outerloop"+o);
        var inner = setInterval(function(){

            console.log("innerloop"+i);
            console.log(new Date());
            i++;
            if(i==max)
            {
                clearTimeout(inner);
                var outer = setTimeout(function(){
                    o++;
                    i=0;
                    if(o==max)
                    {   
                        return;

                    }
                    clearTimeout(outer);
                    rec();
                },delay);
            }
        },delay);
    }
    rec();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top