Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to get setInterval() to start now? [duplicate]

Tags:

javascript

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?

like image 937
Andrew Avatar asked Sep 14 '11 23:09

Andrew


People also ask

How do you run setInterval immediately?

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.

Does setInterval repeat?

The setInterval() method repeats a given function at every given time-interval.

Does the setInterval () function work in JavaScript?

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 ...

How would you stop a setInterval () once it has been set?

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.


1 Answers

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); 
like image 188
jfriend00 Avatar answered Oct 13 '22 09:10

jfriend00