Synchronous

Synchronous execution means that code is executed in a sequential manner, one line at a time.

Each line of code must complete before the next line can be executed.

This can sometimes lead to blocking, where the execution of code is paused until a certain task is completed.

Asynchronous

Asynchronous execution allows code to be executed concurrently.

It doesn't wait for a task to complete before moving on to the next line of code.

Instead, it continues executing other tasks while waiting for the completion of certain operations. This can improve performance and responsiveness in applications.

Problem with Synchronous

Consider the below code:

console.log('Start');

for(let i = 0; i < 1e9; i++) {
    // This loop will take a significant amount of time to complete
}

console.log('End');

The string 'End' won't be printed to the console until the loop has finished counting to 1e9.(due to single threaded nature of JavaScript).

In case of more complex logic, it may require even more management of execution, Hence wherever necessary we use Asynchronous Features of JS.

setTimeout

This function is by default behaves asynchronously.

Arguments:

  1. A callback function: This is the function that will be executed after the delay.
  2. Delay (in milliseconds): This is the amount of time to wait before executing the callback function.
console.log('Start');
setTimeout(
    () => console.log('Halloo'), 5000
);
console.log('End');