Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how javascript single threaded and asynchronous

Tags:

javascript

I went through the link below and understood single threaded javascript and its asynchronous nature a little

https://www.sohamkamani.com/blog/2016/03/14/wrapping-your-head-around-async-programming/

But I still have questions that javascript is single threaded and it always moves in forward direction in sequential manner until it finishes its execution.

Whenever we made call to function which has a callback, that callback will be executed after function receives response. Execution of javascript code continues during the wait time for the response. In this way where execution happening in sequence how callback execution will be resumed once after response received. It's like thread is moving backwards for callback execution.

Thread of execution should always move in forward direction righy?.

please clarify on this.

like image 601
spa Avatar asked Jun 24 '18 06:06

spa


People also ask

How node JS is single threaded and asynchronous?

Node. js is Single Threaded, i.e. it executes the code in a single sequence or direction. At a given time, only a single task/ call is executed. Asynchronous and Single-Threaded: Execution doesn't wait for the current request to complete and moves to the next request/call.

How is JavaScript asynchronous?

Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result.

Is JavaScript is synchronous or asynchronous single threaded or multi threaded?

Javascript is a single threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next. It's synchronous, but at times that can be harmful.

How does JavaScript handle asynchronous calls?

An async function can contain an await expression, that pauses the execution of the function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. You can think of a Promise in JavaScript as the equivalent of Java's Future or C# 's Task.


2 Answers

JavaScript, the language, is not single-threaded, and there exist multi-threaded environments that run JavaScript (for instance, the Java virtual machine via its scripting support). The language itself is largely silent on the topic of threads. It does define a job queue (browser-oriented folks call it an "event loop") and run-to-completion semantics for jobs (see Jobs and Job Queues in the spec). More on that in a moment.

However, most environments (including browsers) run one thread per global environment (or sometimes one thread for multiple global environments), which is why "JavaScript is single-threaded" is so commonly believed. But even on browsers, you can have multiple threads via web workers. They do not share a common global environment, with all the complications that causes, but they can communicate.

Back to your question:

Running on a single thread and having asynchronous callbacks are not at all in conflict. A JavaScript thread works on the basis of a job queue that jobs get added to. A job is a unit of code that runs to completion. When that unit of code is done running to completion, the thread picks up the next job from the queue and runs that. One job cannot interrupt another job (spec link). Jobs running on the main UI thread cannot be suspended in the middle (mostly¹), though jobs on worker threads can be (via Atomics.wait). A thread with a suspended job is completely suspended, it does not pick up other jobs from its queue until it's resumed and completes the job that was suspend.

So for instance, consider:

console.log("one");
setTimeout(function() {
  console.log("three");
}, 10);
console.log("two");

When you run that, you see

one
two
three

in the console. Here's what happened:

  1. A job for the main script execution was added to the job queue
  2. The main JavaScript thread for the browser picked up that job
  3. It ran the first console.log, setTimeout, and last console.log
  4. The job terminated
  5. The main JavaScript thread idled for a bit
  6. The browser's timer mechanism determined that it was time for that setTimeout callback and added a job to the job queue to run it
  7. The main JavaScript thread picked up that job and ran that final console.log

If the main JavaScript thread were tied up (for instance, while (true);), jobs would just pile up in the queue and never get processed, because that job never completes.


¹ "A job is a unit of code that runs to completion." and "A job cannot be suspended in the middle..." Two caveats here:

  1. alert, confirm, and prompt — those 90's synchronous user interactions — suspend a job on the main UI thread while waiting on the user. This is antiquated behavior that's grandfathered in (and is being at least partially phased out).

  2. Naturally, the host process — browser, etc. — can terminate the entire environment a job is running in while the job is running. For instance, when a web page becomes "unresponsive," the browser can kill it. But that's not just the job, it's the entire environment the job was running in.

like image 90
T.J. Crowder Avatar answered Sep 28 '22 05:09

T.J. Crowder


Just to add to T.J.Crowder’s answer above:

The job queue is called an Event Loop which keeps track of all the callbacks that need to be executed. Whenever a callback is ready to be executed ( example: after an asynchronous action has finished ), it is added in the Event loop.

As explained by T.J. Crowder, you can imagine Event loop as a queue. Whenever there is a callback to execute in the loop, the loop takes control of the main thread and executes that callback. The execution of the normal flow stops while this is happening. This way JavaScript can be imagined as a single-threaded language.

You can learn more about Event Loops and how they work in this amazing talk by Philip Roberts.

like image 27
yeshashah Avatar answered Sep 28 '22 05:09

yeshashah