0

In my program, I have few functions and a settimeout function.

function A () { ... };
setInterval(function B, 5000);

Suppose the function A is started and executed for 3 seconds. And the function B s' occurrence was to be in a middle of that 3 seconds. So will the function B will executed after the function A ?? Or will it execute at its' correct time?

TDJ
  • 51
  • 5
  • 1
    Javascript is *single-threaded* - that means, for any page/tab in the browser, only one line of javascript can be running at a time. If your function A takes longer than 5000ms, then function B will have to wait for it to finished, unless you include some provision in function A. – freedomn-m Oct 21 '22 at 15:12
  • Note: that includes any updates to the UI - so if your function A takes >5000ms, then your UI will also be "*frozen*" for 5seconds+ – freedomn-m Oct 21 '22 at 15:14
  • @freedomn-m Suppose the 5th execution of the function B was to execute at the middle of function A is executing. So after the function A is executed, will it be the 5th execution (as soon as the A is completed) or 6th execution (5000 ms after the 5th execution try)?? – TDJ Oct 21 '22 at 15:23
  • Honestly, I think a very quick test would give you that answer. – freedomn-m Oct 21 '22 at 15:36
  • 1
    Does this answer your question? [Why is the \`setTimeout\` callback called after function execution, even if the delay is 0 ms?](https://stackoverflow.com/questions/61580335/why-is-the-settimeout-callback-called-after-function-execution-even-if-the-de) or this answer: [Javascript event queue and setTimeout](https://stackoverflow.com/questions/34691428/javascript-event-queue-and-settimeout) – freedomn-m Oct 21 '22 at 15:37
  • Note you have `setTimeout` not `setInterval` so they'll only be one call to functionB in your example. – freedomn-m Oct 21 '22 at 15:39
  • @freedomn-m thanks for your help. So how would it happen for setInterval function? honestly I wanted to know about setInterval function. I updated the question – TDJ Oct 21 '22 at 16:43
  • @TDJ `A` will finish executing before `B` runs. – Dave Newton Oct 21 '22 at 17:55

0 Answers0