28 November 2016

As web applications become more responsive and advanced today, users may encounter problems from your HTML5 web applications from non-responding script errors to pages that actually hangs forever. Fortunately, thanks to HTML5 web development has given a dose of power that was used to be available to native desktop applications known as the multi-threading.

Most of my career as a programmer/software developer has revolved around resolving performance issues. I guess there's only a handful in this country who does that.
Moving on the topic, multi-threaded programming involves dealing with daemons or background processes or concurrent processes, involves management of buffers, queues asynchronously in order for an application to run smoothly when it's subjected to millions or billions of transactions per second(!).

Introducing the Web Worker, Web Worker is a Javascript API available in all browsers that support HTML5, it works the same way as the Java Thread is mainly used in desktop (SWING, JFC, RCP) and application servers (Apache, JBoss etc). In simple terms, the purpose is to keep the application running smoothly on any given condition.
How the Web Worker Works? When an instance of a Web Worker is created, the browser creates a background daemon in order for a web page to run smoothly. One example is when user is querying large chunk of data and at the same scrolling the page, the application must not prevent the user from doing other tasks while the data is loading.

A working sample, while some web developers will dive and start coding on Web Worker API directly, I decided to use an open source web worker queue library from Github https://gist.github.com/kig/1188381 , the main reason for going on this strategy is to simplify handling worker pool or queue that is not readily available in the native HTML Web Worker API.

// Add an onfinish event handler. // Fired when the queue is empty and all workers // are free. crew.onfinish = function() { console.log('Work Crew: All work in queue finished!' + " -- " + new Date()); };
The code above creates 4 instance of the Web Worker and add multiple work units to the worker it can be hundreds or thousands of tasks but the thing is it will keep your app from freezing, that is if your app really has large amounts of data.