Understanding Asynchronous in javascript

Heru Hartanto - Dec 7 '21 - - Dev Community

Let's me explain with a simple example:

console.log('First log');
console.log('Second log');
console.log('Third log');
Enter fullscreen mode Exit fullscreen mode

As we can see, every line of code will waits for previous line to complete execution before execute next line. this is called with synchronous.

Here another example:

console.log('First log');
setTimeout(()=>{
    console.log('Second log');
},2000)
console.log('Third log')
Enter fullscreen mode Exit fullscreen mode

setTimeout function will wait for milisecond time that set in second argument and executes anonymous function in the first arguments

First log
Third log
undefined
Second log
Enter fullscreen mode Exit fullscreen mode

As we can see, Third log does not wait for Second log to execute, the method of not waiting for the previous code to complete is called asynchronous.

When we need asynchronous ?

The best way to use asynchronous is when your website working with server to fetching data or getting response, instead of waiting all data from server fully loaded that maybe takes more than one minutes (depend on speed of your internet and server speed to resolve request) you could use asynchronous to make sure that code ahead will execute and javascript will not waiting server response to complete.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player