Reputation: 992
I'm learning about js closure from this so post : How do JavaScript closures work?.
I wanted to experiement so I tried creating a loop by creating a function that use callback on the function itself, will doing that I increment an argument and show the result.
At first it didn't worked thent I changed the way I increment my argument and it worked :
function test1(i1){
console.log("test1 : "+i1.toString());
setTimeout(function(){test1(i1++);},2500);
}
function test2(i2){
console.log("test2 : "+i2.toString());
setTimeout(function(){test2(++i2);},2500);
}
test1(0);
test2(0);
Only changed the i++ to ++i.
The output is the following:
test1 : 0
test2 : 0
undefined
test1 : 0
test2 : 1
test1 : 0
test2 : 2
test1 : 0
test2 : 3
test1 : 0
test2 : 4
test1 : 0
test2 : 5
Why does the first step doesn't work?
Edit 2 : I know the diff between i++ and ++i but shouldn't it work anyway?.
Edit: Surely it has something to do with closure ...
Upvotes: 1
Views: 22
Reputation: 10458
in
function test1(i1){
console.log("test1 : "+i1.toString());
setTimeout(function(){test1(i1++);},2500);
}
you are always calling test1() with the same value of i1, and then incrementing it.
Since you always call it with the value 0, you get 0 as the output
test1(i1++)
is equivalent to
test1(i1); // it is always getting called with value = 0
i1++; // later being incremented but not used
while in the other function
function test2(i2){
console.log("test2 : "+i2.toString());
setTimeout(function(){test2(++i2);},2500);
}
it is equivalent to
i2 = i2 + 1;
test2(i2);
Upvotes: 3