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

Why Does `setInterval` Only Run My Callback Once?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 02:02:14372browse

Why Does `setInterval` Only Run My Callback Once?

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!

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