Home > Web Front-end > JS Tutorial > body text

Why Don\'t Parentheses Always Surround Function Calls in `setTimeout`?

Mary-Kate Olsen
Release: 2024-11-23 18:27:17
Original
678 people have browsed it

Why Don't Parentheses Always Surround Function Calls in `setTimeout`?

When to Use Parentheses in Function Calls

When examining the following code:

var myFunction = function() {
  setTimeout(myFunction, 1000);
}
myFunction();
Copy after login

One may wonder why the function call within setTimeout does not require parentheses whereas the independent function invocation does.

Understanding the Distinction

  • myFunction: This name refers to the function definition.
  • myFunction(): The addition of parentheses invokes the function.

Timeout Function Arguments

setTimeout takes a function reference as one of its arguments. In the given code, myFunction is referenced as the callback function.

Parentheses in Timeout Arguments

Including parentheses in setTimeout(myFunction(), 1000) can have unintended consequences if myFunction returns a function (e.g., using arrow functions). In such cases, setTimeout would receive the return value of myFunction instead of the function reference itself. This could lead to repetitive function executions or unexpected behavior.

Therefore, when using setTimeout or similar methods that expect a function reference, it is generally recommended to omit parentheses for the function argument.

The above is the detailed content of Why Don\'t Parentheses Always Surround Function Calls in `setTimeout`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template