How to Add a Delay in a JavaScript Loop

How do I add a delay in a JavaScript loop?

The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.

You may want to use something like this instead:

var i = 1;                  //  set your counter to 1

function myLoop() { // create a loop function

setTimeout(function() { // call a 3s setTimeout when the loop is called

console.log('hello'); // your code here

i++; // increment the counter

if (i < 10) { // if the counter < 10, call the loop function

myLoop(); // .. again which will trigger another

} // .. setTimeout()

}, 3000)

}

myLoop(); // start the loop

Add a delay after executing each iteration with forEach loop

What you want to achieve is totally possible with Array#forEach — although in a different way you might think of it. You can not do a thing like this:

var array = ['some', 'array', 'containing', 'words'];
array.forEach(function (el) {
console.log(el);
wait(1000); // wait 1000 milliseconds
});
console.log('Loop finished.');

... and get the output:

some
array // one second later
containing // two seconds later
words // three seconds later
Loop finished. // four seconds later

There is no synchronous wait or sleep function in JavaScript that blocks all code after it.

The only way to delay something in JavaScript is in a non–blocking way. That means using setTimeout or one of its relatives. We can use the second parameter of the function that we pass to Array#forEach: it contains the index of the current element:

var array = ['some', 'array', 'containing', 'words'];

var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?

array.forEach(function (el, index) {

setTimeout(function () {

console.log(el);

}, index * interval);

});

console.log('Loop finished.');

delay a for loop with javascript

You'll have to go that way:

function jsHello(i) {

if (i < 0) return;

setTimeout(function () {

alert("Hello " + i);

jsHello(--i);

}, 2000);

}

jsHello(5);

Adding 2 Delays In Javascript Loop

You can utilize await inside your loop to wait for a Promise that resolve after 5 seconds to create delays.

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function main() {
for (let i = 0; i < 10; i++) {
showPopup();
await delay(5000);
hidePopup();
await delay(5000);
}
}

Applying delay between iterations of javascript for loop

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));
}

add a delay in a double loop

You could use generators in combination with setinterval to call iterator#next every second. So in the following example, just do yield board whenever you want to wait 1 second.

function* looping() {

let board = "";

for (let y = 0; y < 8; y++) {

for (let x = 0; x < 8; x++) {

board += (x + y) % 2 ? "#" : " ";

yield board;

}

board += "\n";

}

return board;

}

var iterator = looping();

(function iife() {

setTimeout(function() {

var result = iterator.next();

document.querySelector("#result").textContent = result.value;

if (!result.done) iife();

else console.log("Done");

}, 1000);

})();
#result {

white-space: pre;

}

#result::before,

#result::after {

content: '"';

}
<div id="result"></div>

Nested for loop,delay on each loop individually

You could use Promise and async/await to handle sequential call

function taski(i) {
return new Promise(function (resolve) {
setTimeout(function () {
console.log("i is: " + i)
resolve()
}, 1000 * i)
})
}
function taskj(j) {
return new Promise(function (resolve) {
setTimeout(function () {
console.log("j is: " + j)
resolve()
}, 1000 * j)
})
}

async function execute() {
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 1; j++) {
await taski(i)
console.log("delay")
await taskj(j)
console.log("delay")
}
}
}

execute()


Related Topics



Leave a reply



Submit