Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Javascript's setInterval block for function return?

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?

like image 967
Jim Avatar asked Jun 14 '26 17:06

Jim


1 Answers

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

like image 118
Qantas 94 Heavy Avatar answered Jun 16 '26 06:06

Qantas 94 Heavy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!