Skip to content

Instantly share code, notes, and snippets.

@MiguelCastillo
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save MiguelCastillo/ed4455f99fbd9931c964 to your computer and use it in GitHub Desktop.

Select an option

Save MiguelCastillo/ed4455f99fbd9931c964 to your computer and use it in GitHub Desktop.
Sample task manager to handle recursion with trampoline
/**
* Task manager to handle queuing up async tasks in an optimal manner
*/
var TaskManager = {
_asyncQueue: [],
asyncTask: function(task) {
if (TaskManager._asyncQueue.push(task) === 1) {
async(TaskManager.taskRunner(TaskManager._asyncQueue));
}
},
asyncQueue: function(queue) {
if (queue.length === 1) {
TaskManager.asyncTask(queue[0]);
}
else {
TaskManager.asyncTask(TaskManager.taskRunner(queue));
}
},
taskRunner: function(queue) {
return function runTasks() {
var task;
while ((task = queue[0])) {
TaskManager._runTask(task);
queue.shift();
}
};
},
_runTask: function(task) {
try {
task();
}
catch(ex) {
printDebug(ex);
}
}
};
function printDebug(ex) {
if (Factory.debug) {
console.error(ex);
if (ex && ex.stack) {
console.log(ex.stack);
}
}
}
@MiguelCastillo
Copy link
Copy Markdown
Author

@vnadoda Not at all. It can also be function expressions. In my particular example it is a function declaration so that I can define it at the bottom of the containing method to make the code a bit cleaner for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment