In synchronous code execution, each operation is executed one after the other.
What will happen if one of the operations takes a long time to complete? Let’s try to simulate this by creating a long-running task. Add the following function to your code:
Now update your code to include the longtask
function:
When you run this code, you will notice that the longtask
function blocks the execution of the subsequent tasks. The output will be:
This is an example of a blocking operation. The longtask
function blocks the execution of the subsequent tasks until it completes. This can be problematic in applications that require responsiveness and interactivity. For example, in a web application, blocking operations can cause the UI to freeze, making the application unresponsive to user input.
Let’s consider YouTube as an example of a web application. When you click on a video to play it, the video player needs to load the video data from the server. If this operation were synchronous and blocked the main thread, the entire page would freeze until the video data is loaded. However, this does not happen. In fact, while the video data is being loaded, you can still interact with the page, scroll, leave comments, change volume, etc. So how does YouTube perform this resource-intensive operation (of streaming a video) without blocking the main thread?
The web applications you use every day, such as social media platforms, e-commerce websites, and productivity tools, rely on asynchronous programming to provide a smooth and responsive user experience. Asynchronous programming allows you to perform time-consuming operations, such as fetching data from a server or processing large amounts of data, without blocking the main thread of execution.