Home >Web Front-end >JS Tutorial >Why Does My setInterval Callback Only Run Once?
Why Does the setInterval Callback Execute Only Once?
In JavaScript, the setInterval() function is used to execute a function at specified intervals. However, if you encounter an issue where the callback function only executes once, it could be due to an incorrect parameter usage.
Incorrect Usage of Function Call
In the provided code, you're directly executing the timer() function as the first parameter of setInterval():
window.setInterval(timer(), 1000);
This will immediately invoke the timer() function and pass its return value to setInterval(). Instead, you should use a function reference:
window.setInterval(timer, 1000);
Alternatively, you can create an anonymous function to execute at the specified interval:
window.setInterval(function() { console.log("timer!"); }, 1000);
By using a function reference or anonymous function, setInterval() will call your function repeatedly at the specified interval, allowing you to run the counter indefinitely.
The above is the detailed content of Why Does My setInterval Callback Only Run Once?. For more information, please follow other related articles on the PHP Chinese website!