开发者

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 th开发者_C百科e results but don't able to understand the behavior... any help will be appreciated with detail explanation...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜