I have a javascript function function a()
that I want to be executed every 10 seconds.
I found that I can use the setInterval
so that I can do something like: setInverval(a, 10000);
My question is the following:
Does this mean that
i) every 10 seconds the specified function is called (regardless if the previous execution is running/multithreaded way) OR
ii) that the function is called and when this function has finished execution then the next call of the function is scheduled after 10 seconds?
I am basically interested in option 2. If option 1 is what is happening by default then how could I achieve option 2?
I have a javascript function function a()
that I want to be executed every 10 seconds.
I found that I can use the setInterval
so that I can do something like: setInverval(a, 10000);
My question is the following:
Does this mean that
i) every 10 seconds the specified function is called (regardless if the previous execution is running/multithreaded way) OR
ii) that the function is called and when this function has finished execution then the next call of the function is scheduled after 10 seconds?
I am basically interested in option 2. If option 1 is what is happening by default then how could I achieve option 2?
2 Answers
Reset to default 12Basically, setInterval
runs according to option 1, except that if the function takes more than the interval time, it will not be fired again until it has finished and reached the next tick. For example, if you have an interval of 1 second and your function takes 1.5 seconds, it will run on the 2 second tick.
If you want the behaviour of option 2 (run X seconds after function completion), call setTimeout
at the completion of your function instead:
setTimeout(function a() {
// your own code
setTimeout(a, 1000);
}, 1000);
How this works is that it first waits 1 second, then calls the function passed to setTimeout
. At the end of the function, the function itself (a
is the name of the function) is passed to setTimeout
, which then waits another second to call the function again. This continues until JavaScript execution is halted or the timeout is removed by using clearTimeout
.
Note that even if you use setInterval
, the function will never be run concurrently, due to JavaScript's single-threaded nature.
setInterval(a, 10000)
schedules a function to be called every 10 seconds, regardless of the time it took its previous invocations to complete. If you want to schedule the next call for 10 seconds after the completion of the last call, you should call setTimeout(a, 10000)
within the a
function itself, right before it returns, instead of using setInterval
.