-
-
Save aameralduais/46232176af0b73907d388115bbf6a2f2 to your computer and use it in GitHub Desktop.
Javascript Queue for sequencing AJAX requests and other asynchronous tasks. Demo http://jsfiddle.net/rusci/26Dud/6/
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
// Queue class for serializing AJAX calls. | |
// | |
// Inspired by Raynos http://stackoverflow.com/a/4797596/1194060 | |
// | |
// Queue has a public append method that expects some kind of task. | |
// A task is a generic function passed as callback. | |
// Constructor expects a handler which is a method that takes a ajax task | |
// and a callback. Queue expects the handler to deal with the ajax and run | |
// the callback when it's finished | |
function Queue(handler) { | |
var queue = []; | |
function run() { | |
var callback = function () { | |
queue.shift(); | |
// when the handler says it's finished (i.e. runs the callback) | |
// We check for more tasks in the queue and if there are any we run again | |
if (queue.length > 0) { | |
run(); | |
} | |
} | |
// give the first item in the queue & the callback to the handler | |
handler(queue[0], callback); | |
} | |
// push the task to the queue. If the queue was empty before the task was pushed | |
// we run the task. | |
this.append = function (task) { | |
queue.push(task); | |
if (queue.length === 1) { | |
run(); | |
} | |
} | |
} | |
// small handler that launch task and calls the callback | |
// when its finished | |
var queue = new Queue(function (task, callback) { | |
task(function () { | |
// call an option callback from the task | |
if (task.callback) | |
task.callback(); | |
// call the buffer callback. | |
console.log(task, ' done'); | |
callback(); | |
}); | |
}); | |
// Test | |
// Add some tasks to queue... | |
var tasks = [ | |
function (callback) { | |
setTimeout(function () { | |
$('output').insert({ | |
bottom: '<li>Step 1 - ' + new Date() + '</li>' | |
}); | |
callback(); | |
}, 1000); | |
}, | |
function (callback) { | |
setTimeout(function () { | |
$('output').insert({ | |
bottom: '<li>Step 2 - ' + new Date() + '</li>' | |
}); | |
callback(); | |
}, 3000); | |
}, | |
]; | |
for (i = 0; i < tasks.length; i++) { | |
queue.append(tasks[i]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment