مدونات

JavaScript is Single Thread and work Asynchronously at the same time

03

19 سبتمبر

Raneen Medhat

Hello JavaScript lovers ( and haters also ) .
When i start to learn JavaScript i felt there was a lot of concepts in it is illogical and i start to wondering “HOW” ?

How all tutorial and courses teach us that JavaScript is “Single Threaded language ” and in the same time it can works Asynchronously .. ?

Let me explain First what the meaning of :

  • Single Thread: When we say JavaScript is single threaded language that is mean it can do one thing in the run time ( can not do more than one thing in the same time ).

That is mean if we suppose that we have web page contains three requests..
when we send the first request to the server and after waiting the success response ( in case that no failure )… we will send the second request to the server and after waiting the success response ( in case that no failure ) … we will send the third request to … ( The same Scenario )..
Which will make the user nervous because no results will appears in the web page.

This problem solved by Asynchronous Callback Functions

  • Asynchronous: You can do more than thing in the same time without the need to wait the first function to finish.
  • Callback: Function does not execute till something happens (This thing may be function or any thing you determine it).

Example:

Example of call back function

Give your self time to think .. what the output of this code will be ?
if you think that the output will be :
then B then C .. Unfortunately you are wrong !

Before I explain why you are wrong .. let’s agree that JavaScript is Single threaded language which mean it can not do more than one thing in the run time BUT the browser Can.

The browser can access more than thread through Web APIs
Web APIs
 ( something built-in the browser and does not related to JavaScript ) and responsible for :
– AJAX requests.
– Settimeout
– Setinterval

Confused ?
Let me explain what happens
During the run time .. your code execution Occurs in place called Stack..
if your code contains settimout , setinterval or any HTTPrequest .. the stack pass them to the web APIs to run it there.

After the web API finish .. will pass the result to place named Task queue .

And then the tasks in the queue will passed again to the stack through
Event Loop with one condition The Stack Must Be empty.

Now you can answer the question ? what the output of previous code will be ?
Yes you are right .. 
the output will be A then C then B.

Conclusion :

JavaScript is single threaded language and can not do more than one thing in the run time but it can works Asynchronous with browser help through event loop.

تعليقات