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.
Synchronous vs asynchronous execution in 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.
console.log('First'); console.log('Second'); console.log('Third');
console.log('First'); setTimeout(() => { console.log('Second'); }, 500); console.log('Third');
async function greet() { console.log('Hello'); await new Promise(r => setTimeout(r, 1000)); console.log('World'); } greet(); console.log('!');
This program shows synchronous and asynchronous execution. 'Start' and 'End' print immediately. The message inside setTimeout prints after 1 second without stopping the program.
console.log('Start'); setTimeout(() => { console.log('Async task done'); }, 1000); console.log('End');
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.
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.