3

I am a Java developer and beating my head to understand how JS calls function inside a function.

function mainFunction() {
     //some HTTP Call. Callback is done through chaining. (Total execution time: 10s) -> (1)

     //let b = some HTTP Call. Callback is assigned to local variable a. (Total execution time: 5s) -> (2)

      //console.log("Hi") -- (3)

     //Setimeout(500, ......); --(4)

     // some very long piece of code - (Execution time: 60s) -- (5)
}

In timeline, what will be the order of execution of above code?

Do we have any difference (in wait) in Step 1 and Step 2?

Also do we have any difference if these http callbacks leverage AngularJS $http service?

2
  • 1
    Assuming you mean specifically execution of the callbacks for the async ones: 3, 5, 4, 2, 1 Commented Jan 3, 2016 at 16:01
  • To include the initial invocations of the async ones, it would be as follows, where init is the initial call, and cb is the callback: 1init, 2init, 3, 4init, 5, 4cb, 2cb, 1cb Commented Jan 3, 2016 at 16:06

1 Answer 1

2

The way JavaScript executes is, synchronous statement gets executed first and the asynchronous functions are placed aside in a queue. And they gets executed in FIFO manner.

Below is Execution sequence.

Step 1 & 2 have ajax(async) call, so they will get registered but wont get called.

Then step 3 will print console.log as its not asynchronous code.

On step 4 it only take a code and place in the async queue by JavaScript Engine.

Then step 5 will gets called.

So till now our asynchronous queue has Step 1,2 & 4

After Step 5 execution gets completed, compiler evaluates the function/code which have placed in async queue. Step 1, Step 2 & then Step 4, but as per their time evaluation their callback will execute like Step 4(400ms), Step 2 (5s) & then Step 1(10s)

Sign up to request clarification or add additional context in comments.

2 Comments

@squint I updated the answer with their time required for execution.. Thanks for heads up sir. :)
@RohitManglik no..there is not threading mechanism is used to run the code..it will run the code in manner how it gets placed in async queue.. Step 1 then Step 2 then Step 4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.