0
0
Javascriptprogramming~5 mins

Sequential vs parallel execution in Javascript

Choose your learning style9 modes available
Introduction

Sequential and parallel execution help us control how tasks run in a program. Sequential runs tasks one after another, while parallel runs tasks at the same time.

When you want to do steps in order, like making a sandwich step-by-step.
When you want to do many things at once, like cooking multiple dishes at the same time.
When waiting for slow tasks like loading images or data from the internet.
When you want your program to be faster by doing tasks together.
When you want to keep your app responsive while doing background work.
Syntax
Javascript
// Sequential example
console.log('Start');
console.log('Middle');
console.log('End');

// Parallel example with promises
Promise.all([
  fetch('url1'),
  fetch('url2')
]).then(results => {
  console.log('Both done');
});

Sequential code runs line by line, waiting for each to finish.

Parallel code can run tasks at the same time, often using promises or async functions.

Examples
This runs three messages one after another, in order.
Javascript
console.log('First');
console.log('Second');
console.log('Third');
This runs two tasks at the same time and prints results when both finish.
Javascript
Promise.all([
  new Promise(res => setTimeout(() => res('A done'), 1000)),
  new Promise(res => setTimeout(() => res('B done'), 500))
]).then(results => console.log(results));
Sample Program

This program first runs three steps one after another with 1 second wait each. Then it runs three steps at the same time, all finishing after about 1 second.

Javascript
console.log('Sequential start');

function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function runSequential() {
  console.log('Step 1');
  await wait(1000);
  console.log('Step 2');
  await wait(1000);
  console.log('Step 3');
}

async function runParallel() {
  const p1 = wait(1000).then(() => console.log('Parallel Step 1'));
  const p2 = wait(1000).then(() => console.log('Parallel Step 2'));
  const p3 = wait(1000).then(() => console.log('Parallel Step 3'));
  await Promise.all([p1, p2, p3]);
}

(async () => {
  await runSequential();
  console.log('Sequential done');
  await runParallel();
  console.log('Parallel done');
})();
OutputSuccess
Important Notes

Sequential code is easier to understand but can be slower if tasks wait for each other.

Parallel code can be faster but needs care to handle results and errors.

JavaScript uses promises and async/await to help write parallel code clearly.

Summary

Sequential execution runs tasks one by one in order.

Parallel execution runs tasks at the same time to save time.

Use async/await and promises in JavaScript to manage parallel tasks easily.