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
Release: 2024-11-29 02:02:14
Original
301 people have browsed it

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

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

Alternatively, you can also use the following shorter syntax:

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

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!

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