user429035
user429035

Reputation: 461

scope of setTimeout

Let say I have a JS code like this

var num = 0;

function foo(input){
   num = input;

}


function bar(){
  setTimeout(foo(2), 100);//1

  setTimeout(function(){foo(5);},100);//2

  alert("num =" + num);//3

}

what will be the result of using 1 and 3 .....2 and 3 ...i have the results but don't able to understand the behavior... any help will be appreciated with detail explanation...

Upvotes: 2

Views: 836

Answers (1)

user166390
user166390

Reputation:

This isn't an issue of "scope", but rather an issue of timing.

  1. Will have a side-effect of setting num to 2. foo(2) is executed right now and the result (garbage) is passed to setTimeout. (That is, foo(2) is not run as/in the timeout callback.)

  2. Will invoke foo(5) after ~100 milliseconds. The anonymous function acts as the callback which in turn invokes foo(5) that will have a side-effect of assigning 5 to num.

  3. Alerts right now. The value will be "num = 2" because foo(2) ran right now (well, just before ;-) but foo(5) in the callback will run at some time later (and thus has not had a chance to set num).

Happy coding.

Upvotes: 5

Related Questions