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...
For further actions, you may consider blocking this person and/or reporting abuse
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!
🤣🤣🤣
did a flex-box version: jsfiddle.net/bradleygriffith/2dsag...
It's amazing
good work
Ahaha, awesome! 😂
half a second sort for 5 items, very quickly
Unfortunatelly, this cute sorting algorithm doesn't work on values that < 1.
It also poorly works with floats (ex.
[1.5, 1.4, 1.3, 1.2, 1.1]
) and big numbers 😄Try with this example: [10, -100, 500, -20, 35];
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.
This is mostly equivlant with the following code
I think you are a bit crazy, bro ;)
Hey Eugene,
Would you please help me understand how does this happen. Any link or reference would be very helpful.
TIA :)
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 😁
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 😁
This is amazing lol
Lol I just saw a content creator talking about this that she interviewed someone that wrote a code this way.
I mean it works, it's creative. 😂
This is called timeout sort I think :D
It has limitation that if any item of array contained number in billion or millions it will keep in waiting unless the time finish.
how does it sort with timeout? should it not pick items with index
genius
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.
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.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.
I've tried with setTimeout delay of 0, which I expected to run before
third
.but I was surprised to see that
second
was returned last.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...
Thank you, Oscar 🤜
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.
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.
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!
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.
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.
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?
Wow Brian, the video talk from Philip Roberts it's gold! thanks for sharing this!
Great, Brian!
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.
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....
This is a simple yet great explanation of JS async capability and it's relationship to threads thanks for sharing!
Thank you for Nice explanations
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
I still haven't learned about those yet, but I definitely will write something up once I do.
Can someone explain how we got an undefined?
I tried the code on my side and did not get undefined.
Why would it ?
Great !
But can you explain why we get undefined in console!
And what happen when I create a custom async function?
is the the main thread run it?
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)
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)
Hi Brian,
Thanks for sharing this informative article with us
it helped me a lot.
Great explanation. I can easily imagine how js works while reading. Good job!