function printFruits(fruits) {
for (var i = 0; i < fruits.length; i++) {
var curr = i;
console.log(curr);
setTimeout(function() {
console.log(curr);
console.log(fruits[curr]);
}, i * 1000);
}
}
printFruits(["Lemon", "Orange", "Mango", "Banana"]);
Asked
Active
Viewed 38 times
-1

gurvinder372
- 66,980
- 10
- 72
- 94
-
What output are you getting and what is the expected one? – VTodorov Oct 24 '17 at 09:47
-
1Possible duplicate of [How do I add a delay in a JavaScript loop?](https://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) and [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/q/750486/4642212). – Sebastian Simon Oct 24 '17 at 09:48
1 Answers
0
Value of curr
will the one at the time of invocation and by that time value of curr
has already reached 3.
You need to lock the value within a function.
(function(curr){setTimeout(function() {
//console.log(curr);
console.log(fruits[curr]);
}, i * 1000)})(curr);
Demo
function printFruits(fruits)
{
for (var i = 0; i < fruits.length; i++)
{
var curr = i;
//console.log(curr);
(function(curr){setTimeout(function() {
//console.log(curr);
console.log(fruits[curr]);
}, i * 1000)})(curr);
}
}
printFruits(["Lemon", "Orange", "Mango", "Banana"]);

gurvinder372
- 66,980
- 10
- 72
- 94
-
this is working fine, but how it is working that i am unable to understand can you please explain me. thanks in advance. – Ranjith Reddy Keesari Oct 24 '17 at 10:05
-
When the function is being defined current value of `curr` is passed to `setTimeout` via an **IIFE**. Now since `curr` has a local scope within the funciton, its value is not modified when the outer `curr` value is changed and hence it is locked for the execution of funciton. – gurvinder372 Oct 24 '17 at 10:08
-
@RanjithReddyKeesari Everything is explained in the two links I posted under your question. – Sebastian Simon Oct 24 '17 at 10:12
-
funcs[i] = (function(s) { console.log("My value: " + s); })(i) for (var j = 0; j < 3; j++) { funcs[j](); } – Ranjith Reddy Keesari Oct 24 '17 at 11:46