When to Use Parentheses in Function Calls
In the provided code snippet:
var myFunction = function() { setTimeout(myFunction, 1000); } myFunction();
The function call within setTimeout does not require parentheses because setTimeout expects a function reference as an argument. myFunction references the function.
In contrast, myFunction() in the last line calls the function. When using the parentheses with myFunction, it invokes the function and executes its code.
Exception to the Rule
Under certain circumstances, setTimeout(myFunction(), 1000) might make sense. For instance, if myFunction() returns a function itself:
function myFunction() { return function() { alert("ohai") } }
In this case, setTimeout(myFunction(), 1000) does the following:
As a result, an alert will be triggered every second.
The above is the detailed content of When Should I Use Parentheses in JavaScript `setTimeout` Function Calls?. For more information, please follow other related articles on the PHP Chinese website!