Difference between arguments in setInterval calls

时光毁灭记忆、已成空白 提交于 2019-12-18 05:12:33

问题


What's the difference between these setInterval calls and which ones should be used?

setInterval("myFunction()",1000)
setInterval("myFunction",1000)
setInterval(myFunction(),1000)
setInterval(myFunction,1000)

My guess is that JS uses eval() on the first two (strings) and calls the latter two directly.

Also, I don't understand the difference between the calls with and without parentheses. The ones with parentheses call it directly and then periodically call its return value?


回答1:


Correct; the first two use eval and must be avoided at all costs.

Adding () calls the function immediately.

Javascript functions are actually variables that hold functions.
Writing setInterval(myFunction, 1000) passes the value of the myFunction variable to setInterval.
Writing setInterval(myFunction(), 1000) will call myFunction, then pass whatever myFunction returns to setInterval, just like calling any other function.



来源:https://stackoverflow.com/questions/4719758/difference-between-arguments-in-setinterval-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!