Click here to Skip to main content
13,250,043 members (68,804 online)
Click here to Skip to main content
Add your own
alternative version

Stats

13.7K views
295 downloads
27 bookmarked
Posted 18 Oct 2016

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

, 6 Nov 2017
Rate this:
Please Sign up or sign in to vote.
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.

//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.

<!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)

Share

About the Author

O.Nasri
Engineer
France France
Microsoft certified professional in C# ,HTML 5 & CSS3 and JavaScript, Asp.net, and Microsoft Azure.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
PraiseGreat post Pin
HHPanos29-Nov-16 12:16
memberHHPanos29-Nov-16 12:16 
GeneralRe: Great post Pin
ONasri 122027876-Jan-17 10:40
professionalONasri 122027876-Jan-17 10:40 
QuestionI was kind of dissapointed with WebWorkers Pin
Sacha Barber20-Oct-16 6:06
mvpSacha Barber20-Oct-16 6:06 
AnswerRe: I was kind of dissapointed with WebWorkers Pin
ONasri 1220278720-Oct-16 22:22
professionalONasri 1220278720-Oct-16 22:22 
SuggestionClick event binding is wrong Pin
Member 1060880919-Oct-16 23:15
memberMember 1060880919-Oct-16 23:15 
GeneralRe: Click event binding is wrong Pin
ONasri 1220278720-Oct-16 0:07
professionalONasri 1220278720-Oct-16 0:07 
GeneralRe: Click event binding is wrong Pin
gijith20-Oct-16 6:55
professionalgijith20-Oct-16 6:55 
GeneralRe: Click event binding is wrong Pin
ONasri 1220278720-Oct-16 22:11
professionalONasri 1220278720-Oct-16 22:11 
SuggestionRe: Click event binding is wrong Pin
HHPanos29-Nov-16 12:15
memberHHPanos29-Nov-16 12: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 6 Nov 2017
Article Copyright 2016 by O.Nasri
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid