0

I got this code, it's supposed to toggle elements, following a repetitive patron, that will grow up randomly, my start function executes my runp() function at simultaneous, and it got all messy. i would need to wait until runp() finishes to continue executing. Thanks

function runp(patron){
  var x = 0;
  var intervalID = setInterval(function () {
     $("#container"+patron[x]).toggle(1).delay(1000).toggle(1).delay(1000);     

     if (++x === 20) {
         window.clearInterval(intervalID);
     }
  }, 2000);
}

function start(patron, patronl){    
  while (patron.length<20){
    patron.push(rand(1,4));
    runp(patron);
  }   
}
Fil
  • 8,225
  • 14
  • 59
  • 85

1 Answers1

0

You can use .queue()

// alternatively pass randomly shuffled array of elements to `$.map()`
$({}).queue("toggle", $.map($("[id^=container]"), function(el) {
  return function(next) {
    return $(el).toggle(1).delay(1000).toggle(1).delay(1000)
           .promise().then(next)
  }
})).dequeue("toggle")
guest271314
  • 1
  • 15
  • 104
  • 177
  • @Maximiliano Version 2 of linked plnkr randomly sorts elements where `id` begins with `container` randomly, before beginning animations, using approach described at [Randomize the divs that I append into another one](http://stackoverflow.com/questions/25029503/randomize-the-divs-that-i-append-into-another-one) – guest271314 Sep 27 '16 at 01:46