Home >Web Front-end >JS Tutorial >Why Does `setTimeout` Execute My Function Immediately?
When utilizing setTimeout in JavaScript, you may encounter an issue where the function executes instantly, disregarding the specified delay. This anomaly can be attributed to a common pitfall.
The issue arises when you call the function within the setTimeout argument, like this:
setTimeout(testfunction(), 2000);
This syntax immediately invokes testfunction(), and setTimeout schedules the return value of that function call to be executed after the specified delay. As a result, the function runs instantly, and the timer becomes redundant.
To resolve this issue, you should pass the function itself as the argument without invoking it:
setTimeout(testFunction, 2000);
Notice the absence of parentheses after testFunction. This approach ensures that the function execution is scheduled after the delay has elapsed, allowing it to behave as intended.
The above is the detailed content of Why Does `setTimeout` Execute My Function Immediately?. For more information, please follow other related articles on the PHP Chinese website!