2

So basically in the below example, if function1 is ran will it wait until function2 is finished running before test equals 1? Or will it execute function2 on a separate "thread" essentially running function2 and making test equal 1 at the same time? (I think that's what it's called, I'm not too knowledgeable in the whole multithreading thing).

function function1() {
    function2();
    test = 1;
}
Cains
  • 883
  • 2
  • 13
  • 23

3 Answers3

2

Yes, your function1 will wait for function2 to return before continuing. However, your function2 may call things like setTimeout which will themselves not run until function1 completes but function2 will still return before function1 continues even if the code it set to run inside setTimeout has not run yet.

The setTimeout (and setInterval) functions do not work in separate threads but they fake it by running their code when everything else is finished.

Shadow Man
  • 3,234
  • 1
  • 24
  • 35
2

This is a question about how you have the implementation of function2() set up. However almost all javascript is executed in a sequential manner unless a setTimeout(), setInterval() or other event driven mechanic is used for its execution. This however is not true multi-threading, put simply it cheats by just waiting for the rest of the code to execute

However what you have there is saying you execute function2() then wait for it to complete and then execute test = 1, You can almost think of having function2()'s body as being inserted at the beginning of the function1() body. The keyword being "almost". But that should give you an idea of how the JS is executed. However, V8 (Google's javascript engine) can support pseudo-multithreaded environments. While this can technically be done with in normal run of the mill JS it becomes a very big mess very quickly for more information take a look at this Tutorial.

Nomad101
  • 1,688
  • 11
  • 16
1

No, it will wait for function2 to complete.

There are ways to do multi-threading but they require some work, see here for some extra information.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953