Why Does My `setInterval` Callback Only Run Once?
Dec 11, 2024 am 03:36 AMSingle 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial

8 Stunning jQuery Page Layout Plugins

Improve Your jQuery Knowledge with the Source Viewer

10 Mobile Cheat Sheets for Mobile Development
