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

Why Does My setInterval Callback Only Run Once?

Barbara Streisand
Release: 2024-12-03 20:10:16
Original
294 people have browsed it

Why Does My setInterval Callback Only Run Once?

Why Does the setInterval Callback Execute Only Once?

In JavaScript, the setInterval() function is used to execute a function at specified intervals. However, if you encounter an issue where the callback function only executes once, it could be due to an incorrect parameter usage.

Incorrect Usage of Function Call

In the provided code, you're directly executing the timer() function as the first parameter of setInterval():

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

This will immediately invoke the timer() function and pass its return value to setInterval(). Instead, you should use a function reference:

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

Alternatively, you can create an anonymous function to execute at the specified interval:

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

By using a function reference or anonymous function, setInterval() will call your function repeatedly at the specified interval, allowing you to run the counter indefinitely.

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