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
Susan SarandonOriginal
2024-12-07 00:44:12199browse

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);

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);

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

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

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!

Statement:
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