Web workers are one of the most awaited feature of entire HTML 5 specifications. Generally if we think of, the current environment is actually turning towards multicore machines. Today, its verbally every computer has at least 2 cores installed in their machine. Browser are well capable of producing multiple threads that can run in parallel in different cores. But programmatically until we cannot have the flexibility in javascript to run parallel tasks in different cores.
Developers previously uses setTimeout, setInterval or XMLHttprequst to actually create non-blocking calls before. But these are not truely a concurrency. I mean if you still put a long loop inside the setTimeout it will still hang the UI. Actually these works asynchronously taking some of the UI threads timeslices but not actually spawning a new thread to run the code.
As world is moving towards client side Rich User interfaces, we are prone to develop codes that are capable of compute on the client side itself. So going through the line, it is important that the browsers support multiple cores to be used up while executing a javascript.
Web Workers are actually a javascript type that enables you to create multiple cores and run your javascript in a separate thread altogether and communicate the UI thread using Messages, in the similar way as we do for other languages.
Lets look into the code to see how it works.
var worker = new Worker('task.js'); worker.onmessage = function(event) { alert(event.data); }; worker.postMessage('data');
Here we use to load task.js from the Worker. Worker is a type that invokes the code inside a javascript in a new Thread. The start of the thread is called using postMessage on the worker type. Now we have already added a callback to the event onmessage such that when the javascript inside task.js invokes a postMessage this message is received by this callback. Inside task.js we wrote:
self.onmessage = function(event) { // Do some CPU intensive work. self.postMessage("recv'd: " + event.data); };
Here after some CPU intensive work we use self.postMessage to send the data we received from the UI thread and the onmessage event handler gets executed with message received data.
I hope this post comes helpful.
Thank you for reading.