Home >Web Front-end >JS Tutorial >How to Execute setInterval Function Without Delay on the First Run?
Execute setInterval Function Without Delay on First Run
In JavaScript, the setInterval method schedules a function to be executed repeatedly after a specified interval. However, by default, there is a delay before the first execution of the function.
To overcome this delay and execute the function immediately on the first call, we can use one of the following methods:
Method 1: Direct Function Call
This approach involves calling the function manually before calling setInterval.
foo(); setInterval(foo, delay);
Method 2: Self-Triggering Function Using setTimeout
This technique avoids using setInterval and instead relies on the setTimeout function to trigger subsequent executions.
function foo() { // Do stuff... // Schedule next execution setTimeout(foo, delay); } // Start the loop foo();
setTimeout ensures a minimum interval between function calls, eliminating the potential issue of multiple function executions piling up without delay.
Method 3: Immediately Invoked Function Expression (IIFE)
To simplify the process, we can use an IIFE to define the function, call it initially, and start the loop all in one go.
(function foo() { ... setTimeout(foo, delay); })();
This approach offers the advantage of defining the function and initiating the loop simultaneously.
The above is the detailed content of How to Execute setInterval Function Without Delay on the First Run?. For more information, please follow other related articles on the PHP Chinese website!