Image Slide Show Using Web Worker

Introduction

The Web Worker API is used in JavaScript to execute background tasks without affecting the performance of a web page. It is used to perform some activity in a background thread, while the user can continue with normal activities in the foreground. The user can continue to do any task, like clicking, selecting objects, etc., while the web worker runs in the background.

There are various uses for Web Workers; for example, displaying a running timer on the web page or creating a stopwatch, or creating image slide shows.

In this article, I will demonstrate the use of the Web Worker API to create a simple slideshow. The article is extremely simple, and I think it will help new programmers to understand the basic working of web workers.

Using the Code

Before starting to use web workers, we must check whether the Web Worker API is supported by our browser. This can be checked using a simple if statement as follows:

if (typeof(Worker) !== "undefined") {
    // Web worker supported
} else {
    // Web worker not supported
}

Assuming that Web Worker is supported by our browser, our next step would be to create an object to store a web worker reference. We declare the web worker object as a global object and initialize it as follows:

var w;...
if (typeof(w) === "undefined") {
    w = new Worker("scripts/slideimages.js");
}

In the above code, the parameter to the Worker object is the path of the external JavaScript file to be executed by the Web Worker.

Any message coming from the Web Worker can be accessed using the onmessage event handler as follows:

w.onmessage = function(event) {
    document.getElementById("i").src = "images/" + event.data;
}

In the above code, the filename posted by the web worker will be received in the event.data property and will be set as the image source for our <img> tag. (Our images are stored in the images folder.)

A web worker must be terminated after its work is over. Otherwise, it keeps running even after the script execution is over. Also, a web worker can be reused by setting it to undefined. This can be done using the following code:

w.terminate();
w = undefined;

The following is the complete JavaScript code executed by the Web Worker (scripts/slideimages.js):

var ctr = 0;

function slide() {
    ctr++;
    if (ctr > 6) {
        ctr = 1;
    }
    filename = "image" + ctr + ".jpg";
    postMessage(filename);
    setTimeout("slide()", 1000);
}
slide();

In the above code, the Web Worker generates 6 filenames in sequence one by one and posts them using the postMessage() function at an interval of 1 second (1000 milliseconds).

The following is the complete code of our web page to use the Web Worker:

<!DOCTYPE html>
<html>
    <head>
        <title>Web Worker Slide Show</title>
        <style type="text/css">
             body,button
             {
                 background-color:lightblue;
             }
             table
             {
                 border:20px outset blueviolet;
             }
             img
             {
                 width:600px;
                 height:400px;
             }
             button,caption
             {
                 font-size:32px;
                 color:blueviolet;
                 width:100%;
             }
        </style>
        <script type="text/javascript">
             var w;
             function startSlideShow()
             {
                 if(typeof(Worker) !== "undefined")
                 {
                      if(typeof(w) === "undefined")
                      {
                           w = new Worker("scripts/slideimages.js");
                      }
                      w.onmessage = function(event)
                      {
                           document.getElementById("i").src = "images/" + event.data;
                      }
                 }
                 else
                 {
                      alert("Web worker not supported");
                 }
             }
             function stopSlideShow()
             {
                 w.terminate();
                 w = undefined;
             }
        </script>
    </head>
    <body>
        <table>
             <caption>Web Worker Image Slide Show</caption>
             <tr>
                  <td colspan="2"><img id="i" src="images/image1.jpg" /></td>
             </tr>
             <tr>
                  <td><button onclick="startSlideShow()">Start Slide Show</button></td>
                  <td><button onclick="stopSlideShow()">Stop Slide Show</button></td>
             </tr>
        </table>
    </body>
</html>

Conclusion

Web Workers are very useful and also simple to use. I hope readers will find the above article helpful in understanding the basics of Web Workers.