Difference between sync and async code execution

JavaScript |

In this article we will see Difference between sync and async code execution

In JavaScript, synchronous code is executed sequentially, one line of code at a time. Each line of code must be completed before moving on to the next line.

Asynchronous code, on the other hand, allows multiple tasks to be executed simultaneously. Asynchronous code is often used for tasks that involve I/O operations, such as reading from a file or making an API request, which can take a long time to complete.

In synchronous code, when a function is called, it blocks the execution of subsequent code until it has finished executing.
For example:

console.log('Start');
function wait() {
  for(let i=0; i<1000000000; i++) {}
  console.log('Waited');
}
wait();
console.log('End');

In the above example, the wait() function takes a long time to execute, and it blocks the execution of the subsequent code until it is finished.

Start
Waited
End

In asynchronous code, a task is started, and the execution of the subsequent code continues without waiting for the task to finish. When the task is completed, a callback function is executed to handle the result of the task.

console.log('Start');
setTimeout(function() {
  console.log('Waited');
}, 1000);
console.log('End');

In the above example, the setTimeout() function starts a timer for 1000 milliseconds (1 second), and then it returns immediately without blocking the execution of the subsequent code.

After 1 second, the callback function passed to setTimeout() is executed, and it logs the "Waited" message. This is the Difference between sync and async code execution.