Click here to Skip to main content
13,736,547 members
Click here to Skip to main content
Add your own
alternative version


29 bookmarked
Posted 18 Oct 2016
Licenced CPOL

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


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.


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 =;
	//used to iterate the execution of instructions in each 1000 seconds.
		//Send the message back to main thread.
		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>
	<link rel="stylesheet" href="./css/bootstrap.min.css">
    <title>Worker example: One-core computation</title>
	  #idText {
		margin : 2px;
		font-size : 18px;
		background-color : gray;
    <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 :: ";
					$("#idText").css("background-color", '#';
		function startAnimation() {
			worker.postMessage(0);//send message to worker
		function stopAnimation() {
			worker.terminate();//Terminate the worker
			worker = null;
	<span style="width:150px; height:150px; border:2px; 
	border-style: solid;" id="idText">Hello Web Worker</span>
		<input type="button" class="btn btn-success" 

		value="start animation" onclick="startAnimation()"/>
		<input type="button"  class="btn btn-success" 

		value="stop animation" onclick="stopAnimation()"/>

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.


  • v1 18/10/2016: Initial version


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


About the Author

France France
Microsoft certified professional in C# ,HTML 5 & CSS3 and JavaScript,, and Microsoft Azure.

You may also be interested in...


Comments and Discussions

PraiseGreat post Pin
HHPanos29-Nov-16 11:16
memberHHPanos29-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
mvpSacha 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
memberMember 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
HHPanos29-Nov-16 11:15
memberHHPanos29-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.

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