MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Web Workers & Multithreading in JS0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
4.1Microtasks vs Macrotasks (Event Loop Deep Dive)4.2Custom Promise Implementation4.3Async Generators & For-Await-Of4.4Web Workers & Multithreading in JS
HomeTutorialsJavaScript for AdvancedWeb Workers & Multithreading in JS
Custom Error Hierarchies & Prototypes

Web Workers & Multithreading in JS

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Web Workers & Multithreading in Modern JavaScript

While JavaScript is famous for its single-threaded Event Loop, modern browsers provide true hardware-level multithreading via the Web Workers API. Web Workers run scripts in background threads, enabling CPU-intensive operations (image processing, cryptographic hashing, 3D physics, big-data filtering) without blocking the main UI thread.


1. Main Thread vs. Worker Thread

1┌──────────────────────────────────────────────┐
2│ MAIN THREAD │
3│ • Manages DOM, Layout, CSS, and UI events │
4│ • Freezes if heavy calculation runs here! │
5└──────────────────────┬───────────────────────┘
6 │ postMessage(data)
7 ▼
8┌──────────────────────────────────────────────┐
9│ DEDICATED WEB WORKER THREAD │
10│ • Runs in true parallel operating thread │
11│ • NO direct access to DOM or window │
12│ • Has its own global: self / DedicatedWorker│
13└──────────────────────────────────────────────┘

What Workers CANNOT Access:

  • The DOM (document.querySelector, window)
  • parent object
  • Local DOM nodes

What Workers CAN Access:

  • fetch() and XMLHttpRequest
  • IndexedDB
  • WebSockets
  • crypto.subtle
  • setTimeout, setInterval

2. Spawning and Communicating with a Worker

1. The Worker Script (worker.js)

1// worker.js: Runs in isolated background thread
2self.addEventListener('message', (event) => {
3 const { numbers } = event.data;
4 console.log('[Worker] Received array of size:', numbers.length);
5 
6 // Intensive CPU computation (e.g. prime number filtering)
7 const primes = numbers.filter(isPrime);
8 
9 // Send results back to main thread
10 self.postMessage({ primes, count: primes.length });
11});
12 
13function isPrime(num) {
14 if (num <= 1) return false;
15 for (let i = 2; i <= Math.sqrt(num); i++) {
16 if (num % i === 0) return false;
17 }
18 return true;
19}

2. The Main Script (app.js)

1// app.js: Spawns worker from main thread
2const worker = new Worker('worker.js');
3 
4// Listen for results
5worker.addEventListener('message', (event) => {
6 console.log('[Main] Primes computed in background:', event.data.count);
7 hideSpinner();
8});
9 
10// Listen for worker errors
11worker.addEventListener('error', (err) => {
12 console.error('[Main] Worker error:', err.message);
13});
14 
15// Dispatch heavy workload to background thread
16const dataPayload = Array.from({ length: 5000000 }, (_, i) => i + 1);
17worker.postMessage({ numbers: dataPayload });
18 
19// Terminate worker when no longer needed
20// worker.terminate();

3. High-Performance Zero-Copy: Transferable Objects

By default, data passed via postMessage() is cloned using the Structured Clone Algorithm (deep copy), which can be slow for 500MB video buffers or typed arrays.

Transferable Objects transfer memory ownership instantly with zero copy ($O(1)$ transfer time). The sender relinquishes ownership:

1const buffer = new ArrayBuffer(1024 * 1024 * 64); // 64MB Buffer
2 
3// Transfer ownership to worker (Zero-copy transfer!)
4worker.postMessage({ buffer }, [buffer]);
5 
6// In main thread: buffer.byteLength is now 0! It has been moved to worker.
7console.log('Buffer transferred:', buffer.byteLength === 0); // true!

4. Modern Inline Workers with Blob URLs

When building components with Vite or Webpack, you can create Workers dynamically from string literals:

1const workerCode = `
2 self.onmessage = (e) => {
3 self.postMessage(e.data * 2);
4 };
5`;
6 
7const blob = new Blob([workerCode], { type: 'application/javascript' });
8const workerUrl = URL.createObjectURL(blob);
9const inlineWorker = new Worker(workerUrl);

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary advantage of offloading heavy computations to a Web Worker?
Question 2
Can a Web Worker directly manipulate DOM elements via document.getElementById()?
Question 3
What method communicates data between the main thread and a Web Worker?
Question 4
What happens to an ArrayBuffer when it is sent to a Worker as a Transferable Object?
Question 5
How do you immediately terminate an active Web Worker from the main thread?
Next Lesson

Custom Error Hierarchies & Prototypes

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Async Generators & For-Await-OfCustom Error Hierarchies & Prototypes

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext