3

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?

Trishant Pahwa
  • 1,640
  • 8
  • 25

5 Answers5

0

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);
iota
  • 34,586
  • 7
  • 32
  • 51
  • Don't try this example in Firefox, as it may leave the browser unresponsive. (Works fine in Chrome because it uses a separate process for each tab and the browser itself.) – D. Pardal Jul 30 '20 at 17:17
  • It doesn't exactly single threaded. Using setInterval creates a new thread every time it fires a callback that work individually. Look at the answer I have mentioned above. – Trishant Pahwa Jul 30 '20 at 17:33
  • @TrishantPahwa That's incorrect. See here: https://stackoverflow.com/questions/21718774/how-is-javascript-single-threaded – iota Jul 30 '20 at 17:34
  • I don't think it waits, I wish I could paste code in the comments, but try this: save the interval reference, change `4000` to `1000`, then add a `setTimeout` statement that will clear the interval after `2100` milliseconds. You'll see that `"done"` is printed twice, meaning that `setInterval` had the chance to put a second callback in the stack while the first one was still running. Thoughts? – Ghassen Louhaichi Jul 30 '20 at 17:34
  • @hev1 https://stackoverflow.com/a/42507649/6072570, one incorrect example. – Trishant Pahwa Jul 30 '20 at 17:38
  • @TrishantPahwa What do you mean? That isn't multithreaded. – iota Jul 30 '20 at 17:39
  • @hev1 What I mean is. There is a main thread. But, it allows users to create sub-threads. It is like extracting memory from heap and using to stack a function call in it. – Trishant Pahwa Jul 30 '20 at 17:42
  • @TrishantPahwa No, unless you are using WebWorkers, there is only one thread. – iota Jul 30 '20 at 17:43
  • @hev1 Yes, I am not arguing that it is not Single-Threaded. But, what I am saying is, that setInterval creates a new sub-thread. – Trishant Pahwa Jul 30 '20 at 17:45
0

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.

szatkus
  • 1,123
  • 3
  • 13
0

Because of the event loop, the task queue and the single-threaded nature of JavaScript, it would always wait for the function to complete. Synchronous code is never canceled, unless the script is forcefully stopped.

The HTML standard says that timers must:

Wait until any invocations of [the timer initialization algorithm] that had the same method context, that started before this one, and whose timeout is equal to or less than this one's, have completed.

Other timers and browser/runtime tasks would also run between the function. But if the function is running on the main thread, the program would only receive events while the function is not running. In a browser, this would mean that the website would not be interactive for most on the time.

For those reasons, such functions with heavy synchronous computations should be run inside a Worker or split among several tasks (see How to queue a task in JavaScript?).

(I'm assuming "This block takes more than 5 seconds." means that the function returns after 5 seconds.)

D. Pardal
  • 4,876
  • 1
  • 13
  • 32
0

So your setInterval has 2 parameters, a callback and the duration (4s) There are a few things than can affect your interval:

  • your setInteval call a browser API which will start a timer to exactly 4 seconds. Once the timer triggers that 4 seconds, it will append your callback on the JS callback queue. Again, this happens exactly after 4s.
  • Once all the synchronous code will be executed, JS will start running the callbacks in the callback queue, one at a time.

To answer your question: if it's just the code that you posted, it will most likely take exactly 4 seconds. In case you have some heavy operation in your code that takes more than 4 seconds, that code may take longer since it will run only after.

Constantin
  • 1,446
  • 10
  • 14
0

Check this out I found my own answer. What this does is, it spawns a thread to execute the callback function after every timeout that works seperately.

document.write('Part 1:<br>');
setInterval(function() {
    var x = Date.now();
    document.write(x + '<br>');
    setTimeout(function() {
        var y = Date.now();
        document.write(y.toString() + ' : ' + (y-x).toString() + '<br>');
    }, 5000);
}, 2000);
Trishant Pahwa
  • 1,640
  • 8
  • 25