Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript and its one single thread

Reading about that javascript has one single thread to execute its code, lets say the same ajax call is called twice one after the other and there is a callback for this ajax call. Lets say the callback is like this:

function callBackFromJax(){
     var number = 2;
     number = 2+1;
     number = number +5;
     console.info(number)
}

I suppose that if its executing the callback method for the first ajax call, although the second ajax call has already finished:

  1. it has to wait for the single thread to end the execution of the first callback method, right?
  2. Its impossible then that the code for the callback method it being executed at the same time for two threads.
  3. Its like having the functionality synchronized from java in javascript for methods

Thanks!

like image 846
user3254515 Avatar asked Mar 16 '26 02:03

user3254515


1 Answers

It helps to understand that there is a call stack and an event queue. Call stack processes one thing at a time and represents the single threaded nature of JavaScript. The event loop is sort of queue where asyschronus methods are placed and then moved to call stack for processing when they are complete and when the call stack is empty.

Question: it has to wait for the single thread to end the execution of the first callback method, right?
Answer: Yes that is correct.
Question: Its impossible then that the code for the callback method it being executed at the same time for two threads.
Answer: Yes that's also correct
Question: Its like having the functionality synchronized from java in javascript for methods
Answer: That's not correct becasue of event loop and call stack.

Do check out this video https://www.youtube.com/watch?v=8aGhZQkoFbQ on youtube for a detailed explanation.

like image 150
shmit Avatar answered Mar 17 '26 15:03

shmit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!