Fun w/Plain Old JS Queue

by deanpeters

HTML

<h1>Fun w/Plain Old JS Queue</h1>
<h3>We're basically making things async by rolling our own queue.</h3>
<p>Use Chrome Inspector / FireFox FireBug Console to watch things in action</p>
    <script type="text/javascript">
      var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-442503-9']);
        _gaq.push(['_setDomainName', 'deanpeters.com']);
        _gaq.push(['_setCampNameKey', 'jsfiddle']);    
        _gaq.push(['_setCampMediumKey', navigator.userAgent ]); 
        _gaq.push(['_setCampSourceKey', 'internet']);   
        _gaq.push(['_setCampTermKey', 'javascript']);       
        _gaq.push(['_setCampContentKey', document.title ]); 
        _gaq.push(['_trackPageview']);
    
         (function() {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();
    </script>

JavaScript

var AsyncQueue = function(defaultTimeout) {
    this.queue = [];
    this.timeout = (!defaultTimeout) ? 0 : defaultTimeout;
    _this = this;
    
    var _callbackWrapper = function(thecallback, context, params) {
        return function() {
            setTimeout(
                thecallback.apply(context, params),
                _this.timeout
            );
        };
    }    
    
    this.enqueue = function(callbackFunction, paramsArray) {        
        _this.queue.push( _callbackWrapper(callbackFunction, this, paramsArray) );    
    }
    
    this.dequeue = function() {
        while (_this.queue.length > 0) {
            setTimeout(
            (_this.queue.shift())(),_this.timeout);        
        }
     }
}


var myCallback = function(msg) {
    console.log(msg);
}
var myAlert = function(msg) {
    alert(msg);
}
        
q = new AsyncQueue(50000);
q.enqueue(myCallback, ["foo"]);
q.enqueue(myCallback, ["bar"]);
// q.enqueue(function() {alert("bar");});
q.enqueue(myCallback, ["foobar"]);

q.dequeue();
/*
q.enqueue(myCallback, ["my array"]);
q.dequeue();
var myCallback = function(msg) {
    console.log(msg);
}
*/

/*   

var callbackWraper = function(callback, context, params) {
    return function() {
        callback.apply(context, params);
    };
}         

var funQueue = [];
funQueue.push( callbackWraper(callbackFunction, this, ["foo"]) );
funQueue.push( callbackWraper(callbackFunction, this, ["bar"]) );

while (funQueue.length > 0) {
    setTimeout(
    (funQueue.shift())(),
    0 
    );        
}
*/