Single execution ofsetInterval callback:
Consider the following code that aims to create a counter:
function timer() { console.log("timer!") } window.setInterval(timer(), 1000)
However, this code executes the timer function only once. Let's delve into why this issue occurs and how to resolve it.
The problem arises because the first parameter of setInterval should be a function reference, not a function call. In the code above, timer() is called immediately, returning undefined. As a result, setInterval is set to call undefined at a 1000 millisecond interval, which leads to a single execution instead of a continuous loop.
To rectify this, we need to pass a function reference instead of calling the function. Here's the corrected code:
function timer() { console.log("timer!"); } window.setInterval(timer, 1000);
In this corrected version, timer is passed as a reference, allowing setInterval to call it at the specified interval.
Alternatively, we can use an anonymous function as the callback:
window.setInterval( function() { console.log("timer!"); }, 1000)
This approach is shorter but may become less readable when the function becomes more complex.
By implementing these changes, the timer function will now execute repeatedly at the desired interval, ensuring a continuous running counter.
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!