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

Why Does My setInterval Callback Function Only Execute Once?

Susan Sarandon
Release: 2024-12-07 00:44:12
Original
214 people have browsed it

Why Does My setInterval Callback Function Only Execute Once?

setInterval Callback Function Executing Once: Resolved

In this scenario, a counter is intended to run indefinitely. Let's examine a simplified version:

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

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

However, this implementation yields an unexpected result: the "timer" message only appears once.

The issue lies in the setInterval's first argument. Instead of providing a function reference (timer), the code is mistakenly executing the function (timer()). This can be rectified as follows:

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

Alternatively, a more concise (but less readable) syntax can be employed:

window.setInterval(function() {
  console.log("timer!");
}, 1000);
Copy after login

By implementing these corrections, the counter will now execute perpetually, fulfilling the intended functionality.

The above is the detailed content of Why Does My setInterval Callback Function Only Execute 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