I am a newbie to java script and currently reading John Resig’s Pro javascript techniques . While explaining closure he refers to calls like setTimeout("otherFunction()",2000) as instances where new JS developers have problems . I could not understand why this is a problem ? Can some one explain please ?In this http://www.w3schools.com/js/js_timing.asp I am seeing a call like var t=setTimeout("alertMsg()",3000); which looks similar to me .
I am a newbie to java script and currently reading John Resig’s Pro javascript
Share
It’s not “wrong”, it’s just not necessarily “right”, and it’s certainly not recommended.
The
setTimeout()function‘s first parameter can be a string or a function reference / function expression.If you pass a string it will be slower because effectively you are doing an
eval()which is not recommended. More important than speed though is that the scope in which the code in the string executes may not be what you are expecting (and may not be the same in different browsers).By passing a function reference / function expression instead these problems can be avoided.
The “right” syntax for your example is:
Note there are no parentheses after
otherFunction– if there were it would callotherFunction()immediately and pass the return value from that function tosetTimeout().If you need to pass parameters to your function you can wrap it in an anonymous function:
That may seem kind of clunky compared to
setTimeout("otherFunction(param1,param2)", 2000)but again it avoids issues with scope of whereotherFunction,param1andparam2are defined.