I am using the setInterval()
function to call a function every 20 seconds. However, one thing I noticed is that it the first time setInterval()
actually calls the function is at 20 seconds (and not when setInterval()
is called). Here is my current workaround:
dothis(); var i = setInterval(dothis, 20000);
Is there any way to achieve this without having this duplicate code?
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.
The setInterval() method repeats a given function at every given time-interval.
JavaScript setInterval() method. The setInterval() method in JavaScript is used to repeat a specified function at every given time-interval. It evaluates an expression or calls a function at given intervals. This method continues the calling of function until the window is closed or the clearInterval() method is called ...
Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.
Your method is THE normal way way of doing it.
If this comes up over and over, you could make a utility function that would execute the handler first and then set the interval:
function setIntervalAndExecute(fn, t) { fn(); return(setInterval(fn, t)); }
Then, in your code, you could just do this:
var i = setIntervalAndExecute(dothis, 20000);
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