Why Does the setInterval Callback Execute Only Once?
Consider the following issue: you're attempting to create an infinite loop with a counter using setInterval. However, the callback function is only executing once. What could be going wrong?
The provided code is:
function timer() { console.log("timer!") } window.setInterval(timer(), 1000)
The mistake stems from using a function call instead of a function reference as the first argument of setInterval.
Correct Usage:
To fix this, you need to pass the function reference itself, like so:
function timer() { console.log("timer!"); } window.setInterval(timer, 1000);
Alternatively, you can also use the following shorter syntax:
window.setInterval( function() { console.log("timer!"); }, 1000)
The above is the detailed content of Why Does `setInterval` Only Run My Callback Once?. For more information, please follow other related articles on the PHP Chinese website!