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.
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.
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.
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.
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.
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:
console.log
, setTimeout
, and last console.log
setTimeout
callback and added a job to the job queue to run itconsole.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:
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With