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

How to Execute setInterval in JavaScript Without an Initial Delay?

Linda Hamilton
Release: 2024-11-09 13:44:02
Original
854 people have browsed it

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();
Copy after login

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

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!

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