javascript var scope issue
My this question is to understand the concept of scoping(I guess) and also
to ask about its second solution. I have following javascript code
function one() {
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, i*1000);
}
}
function two() {
one();
}
for (var i = 0; i<3; i++) {
two();
}
I have two functions one and two. I am calling function two inside for
loop which runs 3 times. It means function two executes three times.
Inside two, I am calling one. Inside one, I am again using for loop and
declaring i variable and this loop runs 3 times. Inside this loop, I
setTimeout and inside this I am logging out i. This logs out value 3 all
the time whereas I want it to make like 0, 1, 2. WHY?
Solution
In order to make it work, I simply created third function three and place
all the code inside for loop which is inside one and then called function
three inside this for loop and passed i as argument.
so my function three looks like this
function three (i) {
setTimeout(function() {
console.log(i);
}, i*1000);
}
And function one looks like this
function one() {
for (var i = 0; i < 3; i++) {
three(i);
}
}
Now it shows output of 0, 1, 2. Is there another way to solve it? If yes
then please share below.
No comments:
Post a Comment