Difference between arguments in setInterval calls

2019-01-25 21:39发布

问题:

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.