Skip to content

Instantly share code, notes, and snippets.

@markashleybell
Created April 5, 2013 08:44
Show Gist options
  • Save markashleybell/5317659 to your computer and use it in GitHub Desktop.
Save markashleybell/5317659 to your computer and use it in GitHub Desktop.
Queueing asynchronous functions in JavaScript so that each is executed after the previous function has completed; useful when lookup data or templates are required to be loaded before other code can be executed.
<!DOCTYPE html>
<html>
<head>
<title>Queueing Asynchronous Functions in JavaScript</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="queue.js"></script>
</head>
<body>
<p><input type="button" id="process-button" value="Process Queue" /></p>
<div id="output"></div>
</body>
</html>
// Global Queue object
var Queue = (function() {
var _functions = [];
return {
// Add a function to the queue (context: what 'this' should be in the queued function's
// scope, params: an array of parameters to pass to the queued function when called)
add: function(fn, context, params) {
_functions.push(function() {
fn.apply(context, params);
});
},
// Call the next function in the queue
next: function() {
if(_functions.length)
(_functions.shift())();
},
// Start processing the queue
begin: function() {
(_functions.shift())();
}
}
}());
$(function(){
// 'Console' div to display output
var output = $('#output');
// Some functions to queue
var f1 = function(id, callback) { output.append('<div>Function 1 called with param: ' + id + '</div>'); callback(); };
var f2 = function(id, callback) { output.append('<div>Function 2 called with param: ' + id + '</div>'); callback(); };
var f3 = function(id, callback) { output.append('<div>Function 3 called with param: ' + id + '</div>'); callback(); };
// Callback function which kicks off the next item in the queue
var cb = function() {
Queue.next();
};
// Add the functions to the queue
Queue.add(f1, this, ['TEST1', cb]);
Queue.add(f2, this, ['TEST2', cb]);
Queue.add(f3, this, ['TEST3', cb]);
// Begin processing the queue when the button is clicked
$('#process-button').on('click', function(e) {
Queue.begin();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment