Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback function not completed before setInterval's timeout

Tags:

javascript

What would be the result if the callback function is not completed before the timeout of the setInterval function.

For example:

setInterval(function() {
    //  This block takes more than 5 seconds.
}, 4000);

Now the setInterval has a timemout of 4 seconds whereas the callback functions takes 5 seconds to complete. What would happend, would it wait for the function to complete or make execute the callback again in 4 seconds?

like image 632
Trishant Pahwa Avatar asked Oct 28 '25 06:10

Trishant Pahwa


2 Answers

It will wait for the callback to complete, as JavaScript is single-threaded. If you run the below snippet, you will see that 'done' is printed every 5 seconds.

setInterval(function() {
    let curr = new Date;
    while(new Date() - curr <= 5000);
    console.log('done');
}, 4000);
like image 149
Unmitigated Avatar answered Oct 29 '25 21:10

Unmitigated


It depends.

If you put there some computations that happens to take 5 seconds (like looking for prime numbers or something), you'll lock the main thread and another call would be done only when it's unlocked, so in that case after about 5 seconds.

If the part that takes so long is for example a http request it will call the function every 4 seconds as it should. As far as I know there is no mechanism in setInterval that would check if function's promise is done or not.

like image 43
szatkus Avatar answered Oct 29 '25 19:10

szatkus



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!