0
0
Javascriptprogramming~5 mins

Synchronous vs asynchronous execution in Javascript

Choose your learning style9 modes available
Introduction

We use synchronous and asynchronous execution to control how tasks run in a program. Synchronous runs tasks one by one, while asynchronous lets some tasks run in the background so the program doesn't wait.

When you want to do simple tasks step-by-step, like adding numbers.
When you need to wait for data from the internet without freezing the app.
When you want to run a timer or wait for a button click without stopping other code.
When you want to load images or files while still letting the user interact with the page.
Syntax
Javascript
// Synchronous example
console.log('Start');
console.log('Middle');
console.log('End');

// Asynchronous example
console.log('Start');
setTimeout(() => {
  console.log('Middle');
}, 1000);
console.log('End');

Synchronous code runs line by line, waiting for each step to finish.

Asynchronous code can use callbacks, promises, or async/await to run tasks without waiting.

Examples
This is synchronous: logs appear in order.
Javascript
console.log('First');
console.log('Second');
console.log('Third');
This is asynchronous: 'Third' logs before 'Second' because of the delay.
Javascript
console.log('First');
setTimeout(() => {
  console.log('Second');
}, 500);
console.log('Third');
Using async/await: '!' logs before 'World' because of waiting inside greet.
Javascript
async function greet() {
  console.log('Hello');
  await new Promise(r => setTimeout(r, 1000));
  console.log('World');
}
greet();
console.log('!');
Sample Program

This program shows synchronous and asynchronous execution. 'Start' and 'End' print immediately. The message inside setTimeout prints after 1 second without stopping the program.

Javascript
console.log('Start');

setTimeout(() => {
  console.log('Async task done');
}, 1000);

console.log('End');
OutputSuccess
Important Notes

Asynchronous code helps keep programs responsive, especially in web pages.

Use asynchronous methods for tasks like fetching data or waiting for user actions.

Remember: synchronous code blocks the program until it finishes, asynchronous does not.

Summary

Synchronous runs tasks one after another, waiting for each to finish.

Asynchronous runs tasks in the background, letting other code run at the same time.

Use asynchronous to keep programs fast and responsive.