<aside> 🚧
This page is currently under construction. Please check back later.
</aside>
In the past you've learned about control flow. In short: it's the order in which the computer executes statements in a script. In JavaScript this goes from left to right, top to bottom.
Let's look at code execution from another angle. The program that executes your code can do it in two basic ways: synchronous or asynchronous. Whenever code blocks are executed line after line (from top to bottom) we call this synchronous execution. However, when code blocks can be executed without having to wait until a command ends, we call this asynchronous execution.
For instance, after firing off a HTTP network request from inside a JavaScript application running in the browser, the JavaScript engine can continue to do other things, like responding to mouse clicks, making updates to the UI, and so on. When some instance later the HTTP response is received, the application can pick it up and process it.
It important to keep in mind that a computer’s CPU can do (and is expected to do) things much faster (measured in nanoseconds: $10^{-9}$ seconds) than computer networks, or for that matter, any other I/O operations (usually in milliseconds: $10^{-3}$ seconds). So when a network or I/O operation is underway it would be wasteful and unneeded to wait for the operation to complete before doing anything else. An application that would do so would be experienced as unresponsive. Developers would say that the application code blocks while waiting for the I/O operation to complete. Blocking code is something you will want to avoid.
The next two animated images show the difference between asynchronous (non-blocking) code vs synchronous (blocking) code. It involves a simple countdown timer application running in the browser that can work in non-blocking mode and in blocking mode. When the Start button is pressed, it counts down from ten to zero, while updating the page. It also logs the current count to the console.
In the non-blocking version you can immediately observe the following UI issues:
The console however shows the count being decremented as before, i.e. the JavaScript code is still counting down. When the count reaches zero the Start button is no longer shown as depressed. Not shown in this animation is that pressing the Stop button will also not work during the countdown.
Conclusion: The UI issues are caused by blocking code that prevents the browser from updating the UI. In other words, the browser is unresponsive during the countdown.
The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **
