Home > Web Front-end > JS Tutorial > Why Does My `setInterval` Callback Only Run Once?

Why Does My `setInterval` Callback Only Run Once?

Mary-Kate Olsen
Release: 2024-12-11 03:36:11
Original
944 people have browsed it

Why Does My `setInterval` Callback Only Run Once?

Single execution ofsetInterval callback:

Consider the following code that aims to create a counter:

function timer() {
  console.log("timer!")
}

window.setInterval(timer(), 1000)
Copy after login

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);
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template