DEV Community

If Javascript Is Single Threaded, How Is It Asynchronous?

Brian Barbour on June 03, 2019

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 fin...
Collapse
 
karataev profile image
Eugene Karataev

I like asynchronous nature of javascript because it helps me to sort arrays easily. No more bubble, selection, merge or quick sort algorithms. Timeout sort for the win!

let arr = [10, 100, 500, 20, 35];

arr.forEach(item => {
  setTimeout(() => console.log(item), item);
})
// 10 20 35 100 500
Enter fullscreen mode Exit fullscreen mode

🤣🤣🤣

Collapse
 
bradley profile image
Bradley Griffith • Edited

did a flex-box version: jsfiddle.net/bradleygriffith/2dsag...

<div class="sorted-list" id="my-list"></div>

Enter fullscreen mode Exit fullscreen mode
.sorted-list {
  align-items: flex-start;
  display: flex;
  margin: 0 -5px;
}

.sorted-list-item {
  margin: 0 5px;
}
Enter fullscreen mode Exit fullscreen mode
const listEl = document.getElementById("my-list");
const arr = [10, 100, 500, 20, 35];

arr.forEach(n => {
  const itemEl = document.createElement("div");

  itemEl.className = "sorted-list-item";
  itemEl.innerHTML = n;
  itemEl.style.order = n;

  listEl.appendChild(itemEl);
});

Enter fullscreen mode Exit fullscreen mode
Collapse
 
karataev profile image
Eugene Karataev

Ahaha, awesome! 😂

Collapse
 
antonocheret profile image
Anton

half a second sort for 5 items, very quickly

Collapse
 
awcode0x profile image
AWCode0X

It's amazing
good work

Collapse
 
ignore_you profile image
Alex

Unfortunatelly, this cute sorting algorithm doesn't work on values that < 1.

Collapse
 
karataev profile image
Eugene Karataev

It also poorly works with floats (ex. [1.5, 1.4, 1.3, 1.2, 1.1]) and big numbers 😄

Thread Thread
 
saurabh_bakolia_a5f9fc09d profile image
SAURABH BAKOLIA

Try with this example: [10, -100, 500, -20, 35];

Collapse
 
bbarbour profile image
Brian Barbour

In the course I'm doing we had to use setTimeout as a way to avoid stack overflow. I don't think I'd ever do it in a real app, but it was an interesting trick.

Collapse
 
timepp profile image
timepp

This is mostly equivlant with the following code

let arr = [10, 100, 500, 20, 35];
let sorted = 0
for (let i = 0; sorted < arr.length; i++) {
    for (const v of arr) {
        if (v === i) { 
            console.log(v);
            sorted++;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sirius93 profile image
Nandan Kumar

Hey Eugene,
Would you please help me understand how does this happen. Any link or reference would be very helpful.

TIA :)

Collapse
 
karataev profile image
Eugene Karataev

Well, it's a joke and shouldn't be used anywhere in production code.

We iterate on every element (N) in array of numbers and ask a JS engine to log this number in the console after N milliseconds from now. So, these numbers will be logged in a sorted way, because time in our universe flows in one direction 😁

Thread Thread
 
sirius93 profile image
Nandan Kumar • Edited

Yes, indeed it's a joke and should not be used anywhere in production. But it's nice to know how things work, It took me some time to figure out but it was worth it.
Thanks 😁

Collapse
 
fc250152 profile image
Nando

I think you are a bit crazy, bro ;)

Collapse
 
abhiipure1289 profile image
Abhishek Bhardwaj

It has limitation that if any item of array contained number in billion or millions it will keep in waiting unless the time finish.

Collapse
 
aqeel613 profile image
Syed Aqeel

This is called timeout sort I think :D

Collapse
 
jamesqquick profile image
James Q Quick

This is amazing lol

Collapse
 
ryanmattos profile image
Ryan Mattos

genius

Collapse
 
prabhjeet6 profile image
Prabhjeet Singh

how does it sort with timeout? should it not pick items with index

Collapse
 
prahladyeri profile image
Prahlad Yeri • Edited

Not all apps are benefited by javascript's async nature though, only those which are I/O centric. Apps which are more CPU centric like those involving statistical computations or heavy algorithms tend to perform better with non-async languages like java and python.

But when it comes to web development, about 90% of them are pure Database/CRUD or I/O centric apps, hence javascript could be useful in most cases.

Collapse
 
totiiimon profile image
Totiimon

Did you mean to say that some apps are not benefited by the fact that Javascript is single threaded instead? Having async functionality is not a bad thing since languages like Rust or Python have async funtionalities, but what they also have, is multi-threaded capabilities.

Collapse
 
prahladyeri profile image
Prahlad Yeri

Exactly, multi-threading or parallel computing is the key when it comes to a lot of tasks. In fact, to take the full advantage of the 4 cores of your CPU, multi-threading is a must. Async will never be able to do that however efficient it may otherwise be.

It all comes down to what your app needs to do. I/O bound operations are where async shines and you should make full use of that if your app is majorly I/O bound.

Collapse
 
dance2die profile image
Sung M. Kim

I've tried with setTimeout delay of 0, which I expected to run before third.

console.log("first")
setTimeout(() => {
    console.log("second")
}, 0)
console.log("third")
first
third
undefined
second
Enter fullscreen mode Exit fullscreen mode

but I was surprised to see that second was returned last.

Collapse
 
owl profile image
Oscar • Edited

The function in your timeout gets queued as a task. The script runs and once it is done (console.log('third')), the engine can handle the task queue and will execute the timeout callback. So, even though the timeout is zero, the function will not get called immediately.

There is a lot more to the topic and Jake Archibald wrote an amazing article about how this works. I highly recommend reading it:

jakearchibald.com/2015/tasks-micro...

Collapse
 
dance2die profile image
Sung M. Kim

Thank you, Oscar 🤜

Collapse
 
elijahtrillionz profile image
Elijah Trillionz

It's an interesting thing about it.
No matter the delay it will always come after the call stack is empty.
Try using this website loupe to see more of it.

Collapse
 
realtimecarsten profile image
realtimecarsten

In most operating systems, the wait or sleep functions are lower bounds - wait(n) will wait for at least n time-units, but once the time is up, you will never know when your tasked is scheduled next - sometimes that can be really long.

Collapse
 
yogiwisesa profile image
Yogi Wisesa

Hey Brian, coming from the future here. I'm a little bit confused by this statement "Well, we can thank the Javascript engine (V8, Spidermonkey, JavaScriptCore, etc...) for that, which has Web API that handle these tasks in the background. ", if the task is handled in the background so it's mean if the javascript isn't single thread right? since the code is executed in the same time. thank you!

Collapse
 
freelancer2020 profile image
Mostafa

Mastering this topic I considered as a fundamental of being a JavaScript developer, knowing more about JavaScript engine (compiler) , the browser mechanisms and critical rendering path ( CRP ) is very important thing! I advise the developers who want to be a rock in web development field, please go through this topics and learn them carefully and on top of that make a deep understanding of network layer like http requests, responses, cache, cookies, storage, sessions. And related stuff to a browser network.

Collapse
 
aleksandar15 profile image
Aleksandar15

I think you are wrong at this part ...we can thank the Javascript engine (V8, Spidermonkey, JavaScriptCore, etc...) for that, which has Web API....

We don't thank JS Engine for that, because Web API is not part of the JS Engine but the JS runtime environment provided by the Browser, also provided by the browser is the JS Engine itself (V8 for Chrome) and Callback Queue and the Event Loop.
The JS (V8) Engine is made up of Memory Heap & Call Stack.

Furthermore, the purpose of the JS engine is to parse/translate source code that we developers write into machine code that allows a computer to perform specific tasks on its hardware level.

Collapse
 
britain profile image
Britain Green

Great, Brian!

Collapse
 
flrnd profile image
Florian Rand

Wow Brian, the video talk from Philip Roberts it's gold! thanks for sharing this!

Collapse
 
marouaneat95 profile image
marouaneat95

Great article but there's something I can't understand
Isn't the "console" considered a Browser API an not a built-in Javascript object? why doesn't the JavaScript handles the console.log() function to the console API in the same manner it does with well known async functions (setTimeout, setInterval...etc etc) and moves to the next line of code ? Same thing for DOM manipulation which depends on the DOM API?

Collapse
 
ranenguha profile image
Ranen Guha

Nice article Brian with a practical example.

Here is another resource which can be a good primer for newbies in understanding why Javascript is called single-threaded language w3spot.com/2020/07/how-asynchronou....

Collapse
 
vagoel profile image
Varun

Thanks Brian for sharing the video link.Its really amazing and easy to understand the complexity behind JavaScript's call stack/event loop/callback queue.

Collapse
 
oscarcrespo profile image
Oscar Crespo

This is a simple yet great explanation of JS async capability and it's relationship to threads thanks for sharing!

Collapse
 
afattahi54 profile image
afattahi54 • Edited

Great !
But can you explain why we get undefined in console!

Collapse
 
tzah profile image
tzah

And what happen when I create a custom async function?
is the the main thread run it?

Collapse
 
iva_labs profile image
IvaLabs

Wow, this is the clearest explanation of asynchronous JavaScript that I've ever seen. Thank you! Do you, by any chance, feel like trying your hand with closures? :P

Collapse
 
bbarbour profile image
Brian Barbour

I still haven't learned about those yet, but I definitely will write something up once I do.

Collapse
 
nikulgoyani369 profile image
Nikul Goyani

Thank you for Nice explanations

Collapse
 
gecezeeshan profile image
gecezeeshan

I am curious to know, calling below in console give me a number instead of undefined. Can anyone tell me what number it refers to?
setTimeout(() => {
console.log("test")
}, 1000)

Collapse
 
kiransiluveru profile image
kirankumar • Edited

The Number is nothing but ID returned by the SetTimeout Method, Which is useful for clearing/Stopping the settimeout callback, before the callback triggering of give timeout value.
For Example:
clearTimeout(number_returned_by_set_timeout);

clearTimeout(1409)

Collapse
 
red_deguzman_d02719e8a29 profile image
Red De Guzman

Great explanation. I can easily imagine how js works while reading. Good job!

Collapse
 
mahomudgamalfcis profile image
Mahmoud Elgazzar

Hi Brian,
Thanks for sharing this informative article with us
it helped me a lot.