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

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

DDD
Release: 2024-11-23 04:34:21
Original
467 people have browsed it

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();
Copy after login

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")
    }
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template