Home » Tutorials » JavaScript » Web Calculator Powered by Web Worker

Web Calculator Powered by Web Worker

Web Calculator Powered by Web Worker

  • Stumble it!
  • Share

The Idea

In this tutorial, we are going to create a simple web calculator with the function of ‘Add’, ‘Deduct’, ‘Multiply’ and ‘Divide’ function. This tutorial is to show you, how you can utilize web worker to work for your main thread; of course in the future, you would not use web worker for such simple task, but for more elaborate and CPU intensive tasks.

Note: If you are new to Web Worker, please take a look on our previous article ‘Say Hello to HTML5 Web Worker‘ for more details.

Web Calculator Powered by Web Worker

Create A Worker For Arithmetic

Create a web worker for your main thread to handle the arithmetic part as shown below:

function addNumbers(x,y) {
    return x + y;
}

function deductNumbers(x,y) {
	return x - y;	
}
 
function mulNumbers(x,y) {
    return x*y;
}

function divideNumbers(x,y) {
	return x/y;	
}
 
this.onmessage = function (event) {
    var data = event.data;
 
    switch(data.op) {
		case 'add':
        postMessage(addNumbers(data.x, data.y));
        break;
		case 'deduct':
        postMessage(deductNumbers(data.x, data.y));
        break;
        case 'mult':
        postMessage(mulNumbers(data.x, data.y));
        break;
        case 'divide':
        postMessage(divideNumbers(data.x, data.y));
        break;
        default:
        postMessage("Something Wrong.");
    }
};

As you can see above, the ‘onmessage’ was used to received the input data from the main thread that we are going to create later, and assign an appropriate arithmetic function to manipulate the data. Once it done, it will return the result back to main thread.

The Main Thread

Ok, let’s create the main thread that consist of UI to allow user to insert the number for calculation.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Web Calculator Powered by Web Worker | onlyWebPro.com</title>
</head>
<body>
<form>
<input type="text" id="x" value="2" />
<br />
<input type="text" id="y" value="3" />
<br />
<input type="text" id="output" />
<br />
<input type="button" id="addButton" value="Add" />
<input type="button" id="deductButton" value="Deduct" />
<input type="button" id="multButton" value="Multiply" />
<input type="button" id="divideButton" value="Divide" />
</form>
 
<script>
 
/* Check if Web Workers are supported */
 
if (window.Worker) {
	
    var x,y,message;
 
    /* Create a new worker */
    arithmeticWorker = new Worker("arithmetic.js");
 
    /* 
       Add a event listener to the worker, this will
       be called when the worker posts a message.
    */
    arithmeticWorker.onmessage = function (event) {
         document.getElementById("output").value = event.data;
    };
 
    /* Register events for buttons */
	document.getElementById("addButton").onclick = function() {
        /* Get the values to do operation on */
        x = parseFloat(document.getElementById("x").value);
        y = parseFloat(document.getElementById("y").value);
        message = {
            'op' : 'add',
            'x'  : x,
            'y'  : y
        };
 
        arithmeticWorker.postMessage(message);
    }
	
	document.getElementById("deductButton").onclick = function() {
        /* Get the values to do operation on */
        x = parseFloat(document.getElementById("x").value);
        y = parseFloat(document.getElementById("y").value);
        message = {
            'op' : 'deduct',
            'x'  : x,
            'y'  : y
        };
 
        arithmeticWorker.postMessage(message);
    }
	
    document.getElementById("multButton").onclick = function() {
        /* Get the values to do operation on */
        x = parseFloat(document.getElementById("x").value);
        y = parseFloat(document.getElementById("y").value);
        message = {
            'op' : 'mult',
            'x'  : x,
            'y'  : y
        };
        arithmeticWorker.postMessage(message);
    }
	
	document.getElementById("divideButton").onclick = function() {
        /* Get the values to do operation on */
        x = parseFloat(document.getElementById("x").value);
        y = parseFloat(document.getElementById("y").value);
        message = {
            'op' : 'divide',
            'x'  : x,
            'y'  : y
        };
 
        arithmeticWorker.postMessage(message);
    }
    
} else {
		alert("Not Supported");
};
</script>
</body>
</html>

Code Explanation

arithmeticWorker = new Worker("arithmetic.js");

It’s simple and clear, an arithmetic worker was created.

arithmeticWorker.onmessage = function (event) {
     document.getElementById("output").value = event.data;
};

Once we created a worker, we need a function to receive the result that will send back from the worker.

/* Register events for buttons */
	document.getElementById("addButton").onclick = function() {
        /* Get the values to do operation on */
        x = parseFloat(document.getElementById("x").value);
        y = parseFloat(document.getElementById("y").value);
        message = {
            'op' : 'add',
            'x'  : x,
            'y'  : y
        };
 
        arithmeticWorker.postMessage(message);
    }
	
	document.getElementById("deductButton").onclick = function() {
        /* Get the values to do operation on */
        x = parseFloat(document.getElementById("x").value);
        y = parseFloat(document.getElementById("y").value);
        message = {
            'op' : 'deduct',
            'x'  : x,
            'y'  : y
        };
 
        arithmeticWorker.postMessage(message);
    }
	
    document.getElementById("multButton").onclick = function() {
        /* Get the values to do operation on */
        x = parseFloat(document.getElementById("x").value);
        y = parseFloat(document.getElementById("y").value);
        message = {
            'op' : 'mult',
            'x'  : x,
            'y'  : y
        };
        arithmeticWorker.postMessage(message);
    }
	
	document.getElementById("divideButton").onclick = function() {
        /* Get the values to do operation on */
        x = parseFloat(document.getElementById("x").value);
        y = parseFloat(document.getElementById("y").value);
        message = {
            'op' : 'divide',
            'x'  : x,
            'y'  : y
        };
 
        arithmeticWorker.postMessage(message);
    }

And next, several button functions were created to detect the arithmetic function required by user, and giving instruction to the worker by using the ‘postMessage’ function.

That’s all! You’ve done a simple web calculator! Save your document and view it in the supported browser. :)

Read More About HTML5 Articles


  • Create jQuery Responsive Content Slider For Mobile In 5 Minutes!
  • Enhancing Google Map Interactivity with jQuery
  • How To Create jQuery Password Strength Indicator in 10 Minutes!

  • Anonymous

    I didn’t know about this web calculator… its really amazing and workable !! thanks for share! Logo Design Blog

    • http://www.onlywebpro.com onlyWebPro

      Hi NoraReed,

      Thank you! Let’s work together for the future of web industry.

      Cheers!
      The Management of onlyWebPro.com

  • http://www.logoguru.co.uk/pages/logo-design-contest.html Logo Design Contest

    Brilliant resource. Its really nice to have a calculator which is web based, i am sure to apply a practical to create it with this coding provided. Thanks

    • http://www.onlywebpro.com onlyWebPro

      Thank you!

  • http://www.logoguru.co.uk/pages/logo-design-contest.html 99designs vs Crowdspring

    Such a useful and innovative calculating resource. Thanks

  • http://www.webdesignbizz.com/categories-wordpress PSD To Wordpress

    This is a really nice article. I am sure a lot of people will benefit from it. Thanks for your creative posting …

  • Mark

    good resource but it doesnt work in pratical. I tried on notepad++ but it doest add /multiply … could u please figure out why?

Android, iOS Development Tutorials