Crazy JS Loop Alternative

I've been running into a lot of performance issues with JS due to its single threaded nature, particularly when using Titanium SDK on mobile platforms. Some pages might spend several seconds parsing data and outputting it into the UI. Normal for() and while() loops would lock up the app, making it unusable until the loop completed. This loop structure fires intermittently when it's able, allowing more important things (like the UI) to work and run normally until the process is completed.

by cvalleskey

HTML

<ul id="output"></ul>

CSS

body { padding: 20px; background: #ECEDEE; font: 14px/20px Helvetica Neue, sans-serif; }
textarea { background: #323438; color: #EDC; padding: 10px; border: 2px solid #151618; }
ul { margin: 0; padding: 0; }
li { padding: 5px; background: #FFF; color: #444; margin-bottom: 2px; }

JavaScript

var startTime = Date.now();

(function(i,max) {
    (function() {
        if(i < max) {
    
            // Do stuff here
            //document.write(i + "<br />");
            timeout = setTimeout(arguments.callee, 0);
                        $('#output').append("<li>Item " + i + " ("  + (Date.now() - startTime) + "ms)</li>");

        } else {
            clearTimeout(timeout);
            i, max, timeout = null;
        }
        i++;
    })();
})(0,100);