Omar Omar - 7 months ago 8
Javascript Question

jquery .each loop to execute each array item with a delay between them

Please help! I am making an alert system that fires multiple alerts at the same time but I actually want them to appear one at a time so that it looks like a command promt in bash it is the sleep function.

Take a look https://jsfiddle.net/14cmgrLj/10/



function iterateThru (message, status) {
var time = 500;
$.each(alertsArray, function(index, item) {

//setTimeout(function(){ fireAlerts(message, status); }, 1000);
setTimeout(fireAlerts, 100, message, status);

//remove
setTimeout(removeAlert, 4000);
});
// empty array
alertsArray = [];
}





I am calling this function from all over my site. In an effort to make them fire 1-by-1 - everytime my the function is used the object is added to an array and then I use .each to loop through each of them with a setTimeout but they still fire all at once. How can i loop through the array's items with a delay between each.

Thanks in Advance

Answer

You could use jQuery's .delay function to manage the queue jQuery: Can I call delay() between addClass() and such?


Or...

Use an IIFE to manage the incremental wait for each message in the loop.

Fiddle: https://jsfiddle.net/14cmgrLj/11/

It needs a little more work because if you click the create alert button after the first set completes but before they are hidden the timing is all screwy.

function fireAlerts(alerts) {      
  $.each(alerts, function(index, value) {
    // Use IIFE to multiply Wait x Index
    (function(index, value) {
      var wait = index * 1000 + 1000;
      setTimeout(function() {
        // Show Alert
        // [...]
        }
      }, wait);
    })(index, value);
  });
}