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.
Will have a side-effect of setting
num
to 2.foo(2)
is executed right now and the result (garbage) is passed tosetTimeout
. (That is,foo(2)
is not run as/in the timeout callback.)Will invoke
foo(5)
after ~100 milliseconds. The anonymous function acts as the callback which in turn invokesfoo(5)
that will have a side-effect of assigning 5 tonum
.Alerts right now. The value will be "num = 2" because
foo(2)
ran right now (well, just before ;-) butfoo(5)
in the callback will run at some time later (and thus has not had a chance to setnum
).
Happy coding.
精彩评论