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!