HTML5 Web Workers

Everything you need to know about HTML5
Site Admin
Posts: 159
Joined: Sun Jun 26, 2022 10:46 pm

HTML5 Web Workers

Post by C0D3D »

Doing JavaScript works in the background with HTML5 web worker

Example 1

Code: Select all

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Using HTML5 Web Workers</title>
<script>
    if(window.Worker) {
        // Create a new web worker
        var worker = new Worker("/examples/worker.js");
        
        // Fire onMessage event handler
        worker.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        alert("Sorry, your browser do not support web worker.");
    }
</script>
</head>
<body>
    <div id="result">
        <!--Received messages will be inserted here-->
    </div>
</body>
</html>
Terminating a running web worker

Example 2

Code: Select all

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Start/Stop Web Worker in HTML5</title>
<script>
    // Set up global variable
    var worker;
    
    function startWorker() {
        // Initialize web worker
        worker = new Worker("/examples/worker.js");
        
        // Run update function, when we get a message from worker
        worker.onmessage = update;
        
        // Tell worker to get started
        worker.postMessage("start");
    }
    
    function update(event) {
        // Update the page with current message from worker
        document.getElementById("result").innerHTML = event.data;
    }
    
    function stopWorker() {
        // Stop the worker
        worker.terminate();
    }
</script>
</head>
<body>
    <h1>Web Worker Demo</h1>
    <button onclick="startWorker();" type="button">Start web worker</button>
    <button type="button" onclick="stopWorker();">Stop web worker</button>
    <div id="result">
        <!--Received messages will be inserted here-->
    </div>
</body>
</html>
----------------------------------------------------------------------
Together we are one! One we are many... Much Love from one brother to another...
Working together to achieve amazing things!
Teamwork is key.
Knowledge is Power!

4 Basic datatypes.
Strings: Which store a series of characters.
Int: Which store a full integer or number.
Float: A numeric value with a decimal.
Boolean: Only stores True or False and are very useful with if statements

----------------------------------------------------------------------
ImgBB Image upload

Who is online

Users browsing this forum: No registered users and 0 guests