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
Mary-Kate OlsenOriginal
2024-11-09 05:14:02990browse

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

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

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

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!

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