If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
JavaScript me Web Workers एक ऐसे feature हैं जो background threads में scripts को execute करने की सुविधा देते हैं। ये main thread को block किये बिना complex calculations और operations को handle करने में help करते हैं। जिससे UI responsive बनी रहती हैं।
●●●
Background Tasks : Heavy computations जैसे image processing, data parsing, etc. को background में execute करने के लिए।
Asynchronous Processing : Main thread को block किये बिना tasks को asynchronously perform करने के लिए।
Improving Performance : Computationally intensive tasks को background में run करने से overall application performance improve होती है।
●●●
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Worker Example</title>
</head>
<body>
<button id="startWorker">Start Worker</button>
<button id="stopWorker">Stop Worker</button>
<p id="output"></p>
<script src="main.js"></script>
</body>
</html>
let worker;
document.getElementById('startWorker').addEventListener('click', () => {
if (typeof(Worker) !== 'undefined') {
if (!worker) {
worker = new Worker('worker.js');
worker.onmessage = function(event) {
document.getElementById('output').textContent = event.data;
};
}
} else {
console.log('Web Workers are not supported in your browser.');
}
});
document.getElementById('stopWorker').addEventListener('click', () => {
if (worker) {
worker.terminate();
worker = null;
}
});
let i = 0;
function timedCount() {
i++;
postMessage(i);
setTimeout(timedCount, 500);
}
timedCount();
●●●
ऊपर दिए गए example को अब step by step समझते हैं -
1. HTML File : पहले एक Simple HTML structure with two buttons (Start Worker, Stop Worker) और एक paragraph , output को display करने के लिए।
2. main.js
worker variable को define करते हैं।
Start Worker button पर click event listener set करते हैं , अगर Web Workers supported हैं और worker null
है तो new worker instance
create करते हैं जो worker.js
file को load करता है।
worker.onmessage()
event handler को define करते हैं जो worker से messages receive करके output paragraph में display करता है।
Stop Worker button पर click event listener set करते हैं जो worker को terminate करता है और worker variable को null
set करता है।
3. workerjs
timedCount()
function को define करते हैं जो i
variable को increment करता है और postMessage()
method का use करके main thread को message भेजता है।
timedCount()
function को recursive setTimeout()
के साथ call करते हैं ताकि यह हर 500 milliseconds बाद execute होता रहे।
●●●
web workers की कुछ restrictions भी हैं।
Web Workers नीचे दिए गए javascript objects को access नहीं कर सकता है क्योंकि उन्हें external file में define और use किया जाता है।
Parent object
●●●
आपको JavaScript में web worker अच्छे से समझ आ गया होगा।
Loading ...