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

Why Does My setInterval Callback Only Run Once?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 20:10:16298browse

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

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

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

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

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!

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