Home >Web Front-end >JS Tutorial >How Do Parentheses, Quotes, and No Quotes Affect `setTimeout` Behavior in JavaScript?
In JavaScript, setTimeout allows you to schedule a function to execute after a specified delay. There are several ways to use setTimeout with varying syntaxes.
1. with Parentheses:
setTimeout(() => console.log("Callback"), 1000);
In this scenario, an anonymous arrow function is passed as the callback, and the parentheses around it indicate that it's being executed immediately and passed as a reference to setTimeout.
2. Without Quotes or Parentheses:
setTimeout(callbackFunction, 1000);
Here, callbackFunction is a predefined function that is passed as the callback without any quotes or parentheses. The function reference is executed when the delay is complete.
3. Only Using Quotes:
setTimeout("alertMsg()", 1000);
This usage is strongly discouraged as it can lead to security vulnerabilities. It requires the function to be defined as a global variable and uses a string containing the function name. This string is then evaluated and executed as a script.
Key Differences:
The above is the detailed content of How Do Parentheses, Quotes, and No Quotes Affect `setTimeout` Behavior in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!