Reputation: 367
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?
Upvotes: 3
Views: 781
Reputation: 136144
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.
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)
Upvotes: 2