Skip to content

Commit 74032a3

Browse files
committed
feat: add web workers introduction explanation
1 parent e822545 commit 74032a3

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

advanced/webworkers.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// 📌 JavaScript Advanced - Web Workers
2+
3+
// Welcome to the Web Workers section of the JavaScript Advanced tutorial!
4+
// Here, you'll learn how to use Web Workers to run scripts in the background without blocking the main thread.
5+
6+
// Creating a Web Worker
7+
// worker.js (Separate File)
8+
self.addEventListener("message", (event) => {
9+
console.log("Worker received data:", event.data);
10+
let result = event.data * 2;
11+
self.postMessage(result);
12+
});
13+
14+
// Using Web Workers in the Main Script
15+
if (window.Worker) {
16+
const myWorker = new Worker("worker.js");
17+
18+
myWorker.postMessage(10); // Send data to the worker
19+
20+
myWorker.onmessage = function (event) {
21+
console.log("Received from worker:", event.data); // ➝ 20
22+
};
23+
24+
myWorker.onerror = function (error) {
25+
console.error("Worker Error:", error.message);
26+
};
27+
}
28+
29+
// 💡 Web Workers are useful for heavy computations, data processing, and background tasks!

0 commit comments

Comments
 (0)