Concept Flow - Sequential vs parallel execution
Start
Task 1
Task 2
Task 3
End
Start
Task1
Task3
End
Sequential runs tasks one after another. Parallel runs tasks at the same time.
console.log('Start'); setTimeout(() => console.log('Task 1'), 1000); setTimeout(() => console.log('Task 2'), 500); console.log('End');
| Step | Action | Output | Notes |
|---|---|---|---|
| 1 | console.log('Start') | Start | Runs immediately |
| 2 | setTimeout Task 1 scheduled | Task 1 will run after 1000ms | |
| 3 | setTimeout Task 2 scheduled | Task 2 will run after 500ms | |
| 4 | console.log('End') | End | Runs immediately after scheduling |
| 5 | After 500ms, Task 2 runs | Task 2 | Runs before Task 1 because shorter delay |
| 6 | After 1000ms, Task 1 runs | Task 1 | Runs last |
| 7 | All tasks done | Execution complete |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| Task 1 Timer | undefined | Scheduled (1000ms) | Scheduled (1000ms) | Executed |
| Task 2 Timer | undefined | Scheduled (500ms) | Scheduled (500ms) | Executed |
Sequential execution runs code line by line. Parallel execution runs tasks at the same time. JavaScript uses event loop to handle parallel tasks. setTimeout schedules tasks to run later asynchronously. Immediate code runs before scheduled tasks. Tasks with shorter delay run earlier.
What is the main difference between sequential and parallel execution in JavaScript?
Which of the following is the correct syntax to run two promises in parallel using Promise.all?
const p1 = fetch(url1); const p2 = fetch(url2); // What is correct?
What will be the output of this code?
async function test() {
console.log('Start');
await new Promise(r => setTimeout(r, 1000));
console.log('Middle');
await new Promise(r => setTimeout(r, 1000));
console.log('End');
}
test();Find the error in this code that tries to run two async tasks in parallel:
async function runTasks() {
const result1 = await task1();
const result2 = await task2();
return [result1, result2];
}You want to fetch data from three URLs and process results only after all are done. Which code correctly runs fetches in parallel and waits for all?
const urls = ['url1', 'url2', 'url3'];
async function fetchAll() {
// Fill this
}Pass the test and this pattern moves unknown