1

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 ...

1
  • 1
    It's not to do with closure and more to do with the order of execution. Nice edit :) Commented Sep 7, 2017 at 8:50

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Why doesn't it increment the i1 before passing it to test1. Is the calculation made once the function is started? Does it pass the calculation and not the result of the calculation? If yes, why does it "execute" the ++i2 (before?) passing it to test2?
i1++ means, pass the current value of i1 and then increment in the next step, ++i2 means increment first then pass to the function
Okay, I would never have guessed ^^. Thanks you!
If you debug or add another console.log after the test1(i1++) you'll see it does get incremented to 1, it's just that it does this after the function has been executed as has been discussed above!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.