Definition: Async is a short form for “asynchronous”. Synchronous means executing statements one after the other which implies the next statement will get executed only after the previous statement is executed completely. Whereas in Asynchronous calls the next statement gets executed without even waiting for the previous one’s execution.
However, there is some merit in breaking this flow, especially when there is any sort of data transfer over the network involved because it takes time. And that’s where we need to bring in asynchronicity – the ability to override the normal flow of execution, to save time.
How do we do it?
Let us take a sample code to see this.
We might be inclined to believe that what setTimeout() does is, wait for a 1000 milliseconds, then execute the whoSaysGfg() function, and then move on.
Try guessing what the output to this might be ?
If you’re thinking ‘gfg’, that’s incorrect. If you thought ‘fgg’, you’re right. We might tend to think that a timeout of 0 would essentially mean nothing and that the whoSaysGfg() function would be called back immediately.
This has to do with how functions are called and run in the browser. Functions are added to the call stack when a script is run and called from there. Now, when the execution of a function is deferred to the browser, as is the case for setTimeout, the function sits in a queue known as a Task queue or a Callback queue, or a Macro Task queue. It sits there until the entire call stack is empty.
The ‘event loop’ is a service that keeps checking the call stack and the task queue, and schedules the functions on the task queue to get onto the call stack as soon as it’s empty.
Note, that this is not the most optimal solution. Solutions like promises and async-await have come up, but this was the beginning of understanding the concepts of Async.