Home  >  Article  >  Web Front-end  >  When Should I Use Parentheses in JavaScript `setTimeout` Function Calls?

When Should I Use Parentheses in JavaScript `setTimeout` Function Calls?

DDD
DDDOriginal
2024-11-23 04:34:21462browse

When Should I Use Parentheses in JavaScript `setTimeout` Function Calls?

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:

  • Calls the myFunction function, which returns the anonymous function that displays the alert.
  • Sets the returned function as the argument to setTimeout.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn