Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web

Developing a Background Task in Less than 5 Minutes using JavaScript and Web Worker API

4.89/5 (18 votes)
6 Nov 2017CPOL1 min read 37.7K   468  
This article shows you how you implement a background task in JavaScript using Web Worker API

Introduction

The utility of using a background task is:

  • preventing the UI from freezing because of running intensive tasks
  • improving the performance of your JavaScript application

In this article, you will learn in a step by step manner how to execute a background task by using a JavaScript Web Worker API.

Background

This article may be useful for intermediate developers who have some basics in HTML, JQuery, JavaScript.

Using the Code

A) Operating Process

In the following example, we will learn how to handle the main concept of Web Worker API through :

  • Initialization of a Worker (using Worker(url) class) ,
  • Execution of a Web Worker (using postMessage(data) method) ,
  • Exchanging messages between Web Worker and Main thread ,
  • Ending of a Web Worker (using terminate() method).

To know more about Web Worker, I recommend you the following links:

The implemented demo allows users to:

  • Start animation: This action initializes the web worker and sends to it a command to start the animation,  
    The worker will choose a color code from a table, and will return it to the main thread for drawing, 
    finally, the drawing process will change the background color of the 'Hello Web Worker' text.
  • Stop animation: This action ends the worker, and stops animation.

B) Source Code

* Anim.js

This JavaScript file contains the code of the Web Worker.

JavaScript
//Listener for events of message type coming from main thread.
self.addEventListener('message', function(e) {
	//colorArray : is satatic array of hexa color.
    var colorArray = ["d0efb1","9dc3c2","4d7298"];
	//initializes the counter.
	var cp = e.data;
	//used to iterate the execution of instructions in each 1000 seconds.
	setInterval(function(){
		//Send the message back to main thread.
		self.postMessage(colorArray[cp]);
		cp++;
		if(cp == colorArray.length ){
			cp = 0;
		}
	 }, 1000);
	 
}, false);

* Index.html

This HTML file contains the JavaScript code that generates the worker in isolated thread and sends to it instructions to start or stop the animation.

HTML
<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" href="./css/bootstrap.min.css">
    <title>Worker example: One-core computation</title>
	  <style>
	  #idText {
		margin : 2px;
		font-size : 18px;
		background-color : gray;
  	  }
	</style>
    <script src="./js/jquery-2.0.3.min.js"></script>
    <script type="text/javascript">
		var worker = null;//initialization + start the worker
		function init(){
			if(worker == null){
				$("#idText").attr("background-color", "#ffffff");
				worker = new Worker('./js/anim.js');
				worker.onmessage = function (event) {
					console.log("event :: "+event.data);
					$("#idText").css("background-color", '#'+event.data);
				}; 
			}		
		}
		function startAnimation() {
			init();
			worker.postMessage(0);//send message to worker
		}
		function stopAnimation() {
			worker.terminate();//Terminate the worker
			worker = null;
		}
    </script>
</head>
<body>
 
	<span style="width:150px; height:150px; border:2px; 
	border-style: solid;" id="idText">Hello Web Worker</span>
 	<div>
		<input type="button" class="btn btn-success" 
		value="start animation" onclick="startAnimation()"/>
		<input type="button"  class="btn btn-success" 
		value="stop animation" onclick="stopAnimation()"/>
	</div>
</body>
</html>

In Closing

I hope that you appreciated this post. Try to download the source code and do not hesitate to leave your questions and comments.

History

  • v1 18/10/2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)