Skip to content

Instantly share code, notes, and snippets.

@jhthorsen
Created November 22, 2012 10:52
Show Gist options
  • Save jhthorsen/4130541 to your computer and use it in GitHub Desktop.
Save jhthorsen/4130541 to your computer and use it in GitHub Desktop.
Queue callbacks in javascript
/*
* queue.js allow you to run async callbacks in serial.
*/
var Queue = {
callbacks: [],
idle: true,
// Queue.add(function() {});
// Used to add a new function to the callback queue
add: function() {
var cb = arguments[0];
if(window.console) console.log('Queue.add( function )');
Queue.callbacks.push(function() {
if(window.console) console.log('Queue.shift( function )');
Queue.callbacks.shift();
cb();
Queue.idle = true;
Queue.next();
return true;
});
Queue.next();
},
// Queue.ajax(url, function(json) {});
// Used to add a new function to the callback queue which will be fired
// once $.ajax(url, ...) receives data from the server
ajax: function() {
var url = arguments[0][0];
var cb = arguments[0][1];
if(window.console) console.log('Queue.ajax(', url, ')');
Queue.callbacks.push(function() {
$.ajax({
url: url,
success: function(data) {
if(window.console) console.log('Queue.shift(', url, ')');
Queue.callbacks.shift();
cb.call(this, data);
Queue.idle = true;
Queue.next();
}
});
return false;
});
Queue.next();
},
// Queue.next();
// This is called automatically by the async callbacks in add()
// and getJSON()
next: function() {
if(!Queue.idle) return;
var cb = Queue.callbacks[0];
if(!cb) return;
Queue.idle = cb();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment