Print Shortlink

Background threads in JavaScript – II

In the earlier post, we discussed WebWorkers in HTML 5 that can be used to execute JavaScript code in the background. Let’s discuss the use of a WebWorker in this post.

You can create an instance of Worker class by passing the js file as an argument. The code present in the JS file will run as the worker thread. The worker thread and the UI thread can communicate with each other through messages. ie., To pass message you will use postMessage function and to receive message you can use onmessage callback function.

Let’s create a simple example of the worker thread that deals with prime numbers. Wikipedia on WebWorker too has the prime numbers example but let’s do it a bit differently.
Let’s create a text box where you enter a number say 100 and press the button. The number 100 will be posted to the worker thread. The worker code will calculate the list of prime numbers within 100 and pass them to the UI thread one by one. The UI thread will display them in a header element.

The prime number code is created in PrimeNumber.js file. The code is shown below.

//PrimeNumber.js
self.onmessage = function(e){
	var limit = e.data;//100
        self.postMessage("1,2");//1 and 2 are primes
	for(var num=3;num<limit;num+=2){
		var prime = true;
		for(var j=3;j<(num/2);j+=2){
			if(num%j == 0) 
				prime = false;
		}
		if(prime)
			self.postMessage(num);
	}
	self.postMessage("Over");
};

The onmessage function receives the limit from the UI thread and starts computing the number of prime numbers. Every prime number is passed on to the UI thread using postMessage function. When it’s done computing, a message “Over” a passed on to the UI thread.

The html file PrimeNumber.html that consumes the worker is shown below.

<!DOCTYPE html>
<html>
	<head>
		<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
		<script>
			var primeNumberWorker;
		
			$().ready(function(){
				if(window.Worker){
					$("#findPrimesBtn").on("click",findPrimes);
					primeNumberWorker = new Worker("PrimeNumber.js");		
					primeNumberWorker.onmessage = function(e){
					if(e.data == "Over")
					{
						$("#limit").removeAttr("disabled");
				$("#findPrimesBtn").removeAttr("disabled");
					}
	else{
					var data = $("#infoH2").text();
					data += e.data + ", ";
					$("#infoH2").text(data); 				}};
			  }
			else{
				alert("Worker is not supported");
			}
			});
			function findPrimes(){
				$("#infoH2").html("");
				$("#limit").attr("disabled","disabled");
				$(this).attr("disabled","disabled");
				primeNumberWorker.postMessage(parseInt($("#limit").val()));
			}
		</script>
	</head>
	<body>
		Limit <input type="text" id="limit">
		<input type="button" value="Find Primes" id="findPrimesBtn">
		<h2 id="infoH2"></h2>
	</body>
</html>

In the code above, we create a Worker object by passing the PrimeNumber.js file as the argument. When the findPrimes button is clicked we post the number as a message to the worker thread. The output from the worker thread is displayed in the infoH2 header tag.

You can execute this page in FireFox 11.0. If you notice, all that we have used is onmessage callback and postMessage methods. The problem executing this with Firefox is it does consume a lot of memory as Webworkers are pretty memory intensive.

Leave a Reply