Saturday, January 26, 2013

JavaScript mini TPL library: RunAsync

Having learned about HTML5 Web Worker functionality, and that most of the modern browsers implement it, together with the File API BlobBuilder capability I thought about building a library that resembles C#'s Task Parallel Library, allowing JavaScript to be executed in a background thread, but at the same time, adding the ability to dispatch execution to the UI thread and also invoke callbacks and continuations to a "task". I figured the dispatcher functionality was important since usually whatever is executed in the background can/probably will need to interact with the UI while executing. Also this opens a door to use UI frameworks such as jQuery and/or any other DOM access. The problem of passing state while dispatching to the UI thread still exists, but it's on my queue to be solved.

Do check GitHub's page: https://github.com/ricmrodrigues/runasync 

Usage:

Task:
Task.run(function([parameters]) { } [, Array parameters]) returns Promise
Dispatch execution to the UI thread (from within a Task.run or continueWith function callback):
dispatch(function() {})
Promise:
//'when' executes in the UI thread, immediately after the background thread finishes
when(function([parameters]) { }) return Promise
//'continueWith' spins up a new task with the callback provided
continueWith(function([parameters]) { }) returns Promise

Performance:

Running code synchronouslyhttp://jsfiddle.net/UejYX/3/
Example:
for (var x=1;x<=3;x++) {
    (function(idx) {
        var task = Task.run(function(idx) {                
            var response = 0,
                max = (89000000*(idx*3));

            dispatch(function() {
                //do some DOM manipulation that gets executed in the UI thread
            });         

            for (var i=0;i<max;i++) {
                i++;
                if (i === max - 1) response = i;        
            }
            return response;
        }, [idx]);

        task.when(function(value) {
            console.log("executed from UI thread");
        });

        task.continueWith(function(value) {
            //execute something else asynchronously
        });     
    })(x);
}