How to add delay using setTimeout for every iteration? [duplicate] - javascript

This question already has answers here:
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 7 years ago.
This creates a 2 second delay and runs the loop. I need to create a 2 second delay for every iteration, not just once.
var myArray = ['test1','test2','test3'];
function doSetTimeout(index) {
setTimeout(function() { console.log(myArray[index]) }, 2000);
}
var index;
for (index = 0; index < myArray.length; ++index) {
doSetTimeout(index)
}
Expected result would be:
test1
(2 second delay)
test2
(2 second delay)
test3

Just multiply your delay by the index
var myArray = ['test1','test2','test3'];
function doSetTimeout(index) {
setTimeout(function() { console.log(myArray[index]) }, index * 2000;
}
var index;
for (index = 0; index < myArray.length; ++index) {
doSetTimeout(index)
}

Related

Inconsistent output using do/while and for loop in asynchronous JavaScript using let to declare the variables [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 3 months ago.
Why do I get a different output when using a do/while loop in the code below?
function logNum() {
let counter = 0;
do {
counter += 1;
setTimeout(() => console.log(counter), counter * 1000);
} while(counter <= 10);
}
logNum();
The above code outputs number 11 ten times. Expected output was numbers 1 to 10. But when I use a for loop, it works as expected as shown below. Why?
function logNum() {
for (let counter = 1; counter <= 10; counter += 1) {
setTimeout(() => console.log(counter), counter * 1000);
}
}
logNum();
Updated working code from example 1:
function logNum() {
let counter = 0;
do {
let num;
counter += 1;
num = counter;
setTimeout(() => console.log(num), num * 1000);
} while(counter < 10);
}
logNum();
The first increments the counter very quickly and then when the setTimeout function triggers, the counter has already been incremented.
Run this below and you will see.
function logNum() {
let counter = 0;
do {
counter += 1;
console.log('A in loop',counter),
setTimeout(() => console.log('A in timeout',counter), counter * 1000);
} while (counter <= 10);
}
function logNum2() {
for (let counter = 1; counter <= 10; counter += 1) {
setTimeout(() => console.log('B',counter), counter * 1000);
}
}
logNum()
logNum2()
Update. I've just re-read the question - This answer is here:
What is the scope of a 'while' and 'for' loop?

javascript how to fix pitfalls counter [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 4 months ago.
I'm trying to run a for loop and print the current index without use let
here my code:
function init() {
for (var index = 0; index < 5; ++index) {
setTimeout(() => {
console.log(index);
}, index);
}
}
I expected to: 0 1 2 3 4
but i get 5 5 5 5 5
Once the Var replace in Let the problem will be solved
I want to stay with Var
How can the problem be solved?
Thanks
function init() {
for (var index = 0; index < 5; ++index) {
const i = index;
setTimeout(() => {
console.log(i);
}, i);
}
}
This should work.

Print pattern lines using delay loop callback javascript [duplicate]

This question already has answers here:
async loading javascript with document.write
(5 answers)
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 3 years ago.
I have a code to print a pyramid pattern using callback in javascript.
Right now I am able to load entire code after 2 sec.
I need to print pattern rows after 2 sec interval of time instead loading it at a whole using call back and promises . How can I do it ?
var n = 5;
for (var i = 0; i < n; i++) {
getStar(i, n).then(star => console.log(star));
}
function getStar(i, n) {
return new Promise((resolve, reject) => {
var str = '';
for (var j = 1; j < n - i; j++) {
str = str + ' ';
}
for (var k = 1; k <= (2 * i + 1); k++) {
str = str + '*';
}
setTimeout(() => {
resolve(str);
}, 2000)
})
}

Javascript loop showing same value 10 times [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
Why is this function only sending the number 10 ten times. I want it to send 1... 2 ... 3 ... 4 ... 5 and so on
but instead its showing
10....10.... 10... 10... I'm not sure why it would.
How do I make a loop that returns distinct values?
for (i = 0; i < locations.length; i++) {
setTimeout(function() { alert("test"+i.toString()) ; }, 100);
}
How do I make a loop that returns distinct values?
You can do this by using a closure (pass i back into an immediately invoked function expression (IIFE)). This will maintain the value of i:
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() {
console.log("test" + i);
}, 100);
})(i);
}
To increment the timeout by using the i works the same way. Making sure to wrap the entire timeout call with the IIFE:
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() {
console.log("test" + i);
}, i * 100);
})(i);
}

setTimeout doesn't work JavaScript "style undefined" [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I want to fade in 4 div boxes, one by one.
In css they have the opacity = 0.
Here my JavaScript code:
function fadeIn() {
var box = new Array(
document.getElementById('skill1'),
document.getElementById('skill2'),
document.getElementById('skill3'),
document.getElementById('skill4')
);
var pagePosition = window.pageYOffset;
if (pagePosition >= 1000) {
for (var i = 0; i < box.length; i++) {
setTimeout(function(i) {
box[i].style.opacity = "1";
}, i * 500);
}
}
}
Well, the function has to start if you scroll the page to the position 1000px and called in the body-tag:
Without the setTimeout it works, but with this function the console says:
Uncaught TypeError: Cannot read property 'style' of undefined
I'm a beginner and want to understand JS, so please don't provide an answer using jQuery.
By the time your your timeout runs, the loop has finished processing, so i will always be the last iteration. You need a closure:
for(var i = 0; i < box.length; i++) {
(function(index) {
setTimeout(function() {
box[index].style.opacity = "1";
}, index*500);
})(i)
}
The problem is the scope. When anonymous function executes inside timeout i variable has the last value of the i in the iteration. There are two solutions:
1) Use an IIFE:
for (var i = 0; i < box.length; i++) {
(function (i) {
setTimeout(function (i) {
box[i].style.opacity = "1";
}, i * 500);
})(i);
}
for (var i = 0; i < 5; i++) {
(function(i) {
setTimeout(function() {
console.log(i);//prints out 0 1 2 3 4
}, i * 500)
})(i);
}
2) Using let:
for (let i = 0; i < box.length; i++) {
setTimeout(function (i) {
box[i].style.opacity = "1";
}, i * 500);
}
"use strict";
for (let i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i)
}, i * 500)
}
The let statement declares a block scope local variable, optionally
initializing it to a value.
Keep in mind let is feature fo ecmaScript 6.

Categories