Home  >  Article  >  Web Front-end  >  How to Execute setInterval in JavaScript Without an Initial Delay?

How to Execute setInterval in JavaScript Without an Initial Delay?

Linda Hamilton
Linda HamiltonOriginal
2024-11-09 13:44:02813browse

How to Execute setInterval in JavaScript Without an Initial Delay?

Executing setInterval Without Initial Delay

In JavaScript, the setInterval method repeats a function execution at specified intervals. However, by default, there is a noticeable delay before the first execution. This article explores ways to eliminate this delay.

While it is possible to call the function manually prior to initiating the timer, it is not ideal and can be forgotten easily. A more effective approach is to utilize setTimeout within the function itself:

function foo() {
   // Execute function body
   // ...

   // Schedule subsequent execution
   setTimeout(foo, delay);
}

// Start the cycle
foo();

This approach ensures a consistent interval between function executions while providing the flexibility to terminate the loop by omitting the setTimeout call when necessary.

Alternatively, an immediately invoked function expression (IIFE) can be employed to create and start the loop in a single step:

(function foo() {
    ...
    setTimeout(foo, delay);
})();

This method eliminates the initial delay and simplifies the setup process by encapsulating the function and execution schedule within a self-contained block. Whether you prefer the direct calling, setTimeout method, or IIFE approach, these techniques offer convenient solutions for executing setInterval without the unwanted initial delay.

The above is the detailed content of How to Execute setInterval in JavaScript Without an Initial Delay?. 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