Home > Web Front-end > JS Tutorial > How Can I Make `setInterval` Execute Immediately in JavaScript?

How Can I Make `setInterval` Execute Immediately in JavaScript?

Mary-Kate Olsen
Release: 2024-11-09 05:14:02
Original
948 people have browsed it

How Can I Make `setInterval` Execute Immediately in JavaScript?

Executing setInterval Immediately

When using JavaScript's setInterval method, it is often desirable for the function to execute immediately and then continue executing with the specified timer delay. However, by default, setInterval does not execute the function immediately.

Initial Execution without Delay

The simplest approach is to manually call the function immediately before invoking setInterval:

foo();
setInterval(foo, delay);
Copy after login

Alternative Method with setTimeout

Alternatively, you can use setTimeout to trigger subsequent executions of the function:

function foo() {
  // ...
  setTimeout(foo, delay);
}
foo(); // start the cycle
Copy after login

This method ensures a minimum delay between function calls and simplifies cancellation.

Using an Immediately Invoked Function Expression (IIFE)

This technique combines function definition and initial execution in a single statement:

(function foo() {
  ...
  setTimeout(foo, delay);
})();
Copy after login

The IIFE defines the function and starts the loop in one line of code, providing a concise and efficient solution.

The above is the detailed content of How Can I Make `setInterval` Execute Immediately in JavaScript?. 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