Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
The moving, singing, and dancing you see on web pages are a result of functions that wait for you to activate them. Imagine tiny magical elves lying in wait, listening for your key press or the hovering of your keyboard. These elves spring to action once they hear a specific “event” ie. a click.
The tiny elves(ie. event functions) then go to a specific HTML element that they’ve been assigned to and make it move, sing–or whatever they were told to make it do. This doesn’t happen all at once. The tiny elves wait for one event at a time. So, each elf corresponds to a specific event and they have to wait for their turn in a line.
What is a single-threaded language?
Simply put, a single threaded language uses a single call stack, meaning that it can only fire one event at a time. If you’re not exactly sure how to conceptualize a call stack, just picture a Jenga stack.
What is non-blocking, asynchronicity, and concurrency?
Well, let us try to understand what blocking is first. In a nutshell, blocking is the traffic caused by too many synchronous calls. Imagine a narrow exit that funnels drivers into a single lane road. That road is guarded by a traffic police who only allows one car at a time to go beyond his stop sign.
Now imagine the headache you’d have if you’re the fifteenth car in line and you have to get to the emergency room. Similarly, websites coded with blocking code make for a clunky user interface.
Here’s where things get really interesting
We’ve mentioned Web APIs and an event loop. There’s also a callback queue. If you’re getting slightly confused, don’t panic. The comic will explain everything.
- Web APIs: a third party data store that holds a message for however long it is instructed to hold it.
- The callback queue: a loading dock for calls
- The event loop: a little green droid with one simple job — check if the stack is empty. If it’s empty, take an event from the queue and place it onto the stack. Continue to do so while the condition is true.
On a very asynchronous day, all the call operator has to do is load all of the Web API functions, then he can leave the task to both the Web APIs and the mini droid aka the event loop. The Web APIs store the callbacks until they are ready to be staged onto the call back queue. All the event loop (mini droid) has to do is check if the stack is empty and place the callback onto the stack. Meanwhile, the call operator can focus on more important functions, like dinner with the wife.
We’ll deal with callabcks more when we get to functions. Till then, stay coding.
Aggregate valuable and interesting links.
Joyk means Joy of geeK