Click here to Skip to main content
15,885,537 members
Articles / Web Development
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.89/5 (18 votes)
6 Nov 2017CPOL1 min read 36.6K   468   29   9
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)


Written By
Technical Lead
France France
Microsoft certified professional in C# ,HTML 5 & CSS3 and JavaScript, Asp.net, and Microsoft Azure.

Comments and Discussions

 
PraiseGreat post Pin
GoodPanos29-Nov-16 11:16
professionalGoodPanos29-Nov-16 11:16 
GeneralRe: Great post Pin
O.Nasri6-Jan-17 9:40
professionalO.Nasri6-Jan-17 9:40 
QuestionI was kind of dissapointed with WebWorkers Pin
Sacha Barber20-Oct-16 5:06
Sacha Barber20-Oct-16 5:06 
AnswerRe: I was kind of dissapointed with WebWorkers Pin
O.Nasri20-Oct-16 21:22
professionalO.Nasri20-Oct-16 21:22 
SuggestionClick event binding is wrong Pin
Member 1060880919-Oct-16 22:15
Member 1060880919-Oct-16 22:15 
GeneralRe: Click event binding is wrong Pin
O.Nasri19-Oct-16 23:07
professionalO.Nasri19-Oct-16 23:07 
GeneralRe: Click event binding is wrong Pin
gijith20-Oct-16 5:55
professionalgijith20-Oct-16 5:55 
GeneralRe: Click event binding is wrong Pin
O.Nasri20-Oct-16 21:11
professionalO.Nasri20-Oct-16 21:11 
SuggestionRe: Click event binding is wrong Pin
GoodPanos29-Nov-16 11:15
professionalGoodPanos29-Nov-16 11:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.