HTML Web Workers
HTML5 provides a Web Workers API that allows web developers to run scripts in the background, without blocking the main user interface thread. This allows web applications to perform complex operations, such as data processing or image manipulation, without causing the user interface to become unresponsive.
Here's an example of using a Web Worker to perform a time-consuming operation:
html
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<p id="result"></p>
<script>
var worker;
function startWorker() {
if (typeof(Worker) !== "undefined") {
if (typeof(worker) == "undefined") {
worker = new Worker("worker.js");
}
worker.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "Web Workers are not supported by this browser.";
}
}
function stopWorker() {
worker.terminate();
worker = undefined;
}
</script>
In this example, two buttons are created that call the startWorker() and stopWorker() functions when clicked. The startWorker() function checks if the browser supports Web Workers, and if so, creates a new worker using the Worker() constructor, passing in the name of a JavaScript file containing the worker code. The worker.onmessage event handler is used to retrieve the result of the worker operation, and display it in a paragraph element with an id of "result". The stopWorker() function terminates the worker when called.
The Web Workers API can also be used to communicate between the main thread and the worker thread using the postMessage() and onmessage methods.
No comments:
Post a Comment