-
-
Save psiborg/8433734 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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