Asynchronous and Synchronous

Synchronous execution is when statements are simply executed one after the other. Asynchronous execution is when statements don’t have to execute in that rigid order. They can be executed in any order. That is often used to perform multiple tasks simultaneously.

Consider the following analogy. You are doing your household chores. That includes doing the dishes, laundry and cooking your lunch. You can do all those tasks one by one (synchronously). But that isn’t very efficient, is it? So you do them all at once. You pile the dishes and start up the dishwasher. While that happens, you collect the laundry and put it in the washing machine. While it works its magic, you start chopping veggies for lunch. You keep alternating between tasks till all of them are done.

Introduction

Let us understand how JavaScript handles asynchronous code. Most of the languages use a multi-threaded model with pre-emption. JavaScript on the other hand is single threaded by specification. If you don’t understand what that means, a quick google search can be useful. You can also choose to ignore this, as it isn’t really relevant to our discussion.

The problem

JavaScript can do only one thing at a time. That creates a problem when you want to perform operations additional to the main computation. For example:

… perform computation
set timer : After 1000ms, print — “Timer Done”
… perform computation

To process the timer, JS engine has to stop performing computation and wait for 1000ms. When the timer completes, it prints “Timer Done”. After that, it can resume computation. This is not very efficient. Fortunately, there is a way around

#javascript #asynchronous #event-loop #micro-tasks

The Asynchronous Circus
1.15 GEEK