It's there a way to configure the setInterval
method of javascript to execute the method immediately and then executes with the timer
Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set with the required callback.
Usage notes. The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. You can cancel the interval using clearInterval() . If you wish to have your function called once after the specified delay, use setTimeout() .
The setInterval method is used to schedule a function to be executed repeatedly after a period of time. The syntax for this method is this: const timerID = setInterval(function, delay, arg1, arg2, ...) In this case, the delay is the time in milliseconds that the timer should delay successive executions of the function.
The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)
It's simplest to just call the function yourself directly the first time:
foo(); setInterval(foo, delay);
However there are good reasons to avoid setInterval
- in particular in some circumstances a whole load of setInterval
events can arrive immediately after each other without any delay. Another reason is that if you want to stop the loop you have to explicitly call clearInterval
which means you have to remember the handle returned from the original setInterval
call.
So an alternative method is to have foo
trigger itself for subsequent calls using setTimeout
instead:
function foo() { // do stuff // ... // and schedule a repeat setTimeout(foo, delay); } // start the cycle foo();
This guarantees that there is at least an interval of delay
between calls. It also makes it easier to cancel the loop if required - you just don't call setTimeout
when your loop termination condition is reached.
Better yet, you can wrap that all up in an immediately invoked function expression which creates the function, which then calls itself again as above, and automatically starts the loop:
(function foo() { ... setTimeout(foo, delay); })();
which defines the function and starts the cycle all in one go.
I'm not sure if I'm understanding you correctly, but you could easily do something like this:
setInterval(function hello() { console.log('world'); return hello; }(), 5000);
There's obviously any number of ways of doing this, but that's the most concise way I can think of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With