Is it possible to apply a delay to successive iterations of a javascript for-loop using jQuery or underscore? I have a for-loop on my page that I am using to pop up growl notifications when users fulfill certain conditions and if there are multiple conditions I would like to stagger the growl notifications instead of popping up several at the same time. Here is the loop in question:
var badge_arr = response.split("Earned badge:");
//Start at 1 so I'm not getting everything before the first badge
for(i = 1; i < badge_arr.length; i++){
responseStr += badge_arr[i];
//Create growl notification
//badge info echoed back will be of the form
//Earned badge: name: description: imgSource
var badge_info = badge_arr[i].split(':');
var title = 'NEW BADGE UNLOCKED';
var text = 'You just unlocked the badge '+badge_info[0]+': '+badge_info[1];
var img = badge_info[2];
createGrowl(title, text, img);
}
The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console. log("Hello"); setTimeout(() => { console.
JavaScript Promises in For Loops. To use Javascript promises in a for loop, use async / await . This waits for each promiseAction to complete before continuing to the next iteration in the loop. In this guide, you learn how async/await works and how it solves the problem of using promises in for loops.
To create pause or delay in a JavaScript for loop, we should use await with a for-of loop. to define the wait function that returns a promise that calls setTimeout with resolve to resolve the promise in ms milliseconds. Then we define the loop function that runs a for-of loop to loop through an array.
for(i = 1; i < badge_arr.length; i++){
(function(i){
setTimeout(function(){
responseStr += badge_arr[i];
//Create growl notification
//badge info echoed back will be of the form
//Earned badge: name: description: imgSource
var badge_info = badge_arr[i].split(':');
var title = 'NEW BADGE UNLOCKED';
var text = 'You just unlocked the badge '+badge_info[0] +
': '+badge_info[1];
var img = badge_info[2];
createGrowl(title, text, img);
}, 1000 * i);
}(i));
}
Illustration:
for(i = 1; i <= 8; i++){
(function(i){
setTimeout(function(){
document.body.innerHTML += i + "<br/>"
}, 1000 * i);
}(i));
}
I prefer to use self-invoking function that receives a number of iterations:
(function loop(i) {
setTimeout(function () {
console.log('hello world'); // your code
if (--i) loop(i); // iteration counter
}, 5000) // delay
})(10); // iterations count
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With