Last active
August 29, 2015 14:11
-
-
Save MiguelCastillo/ed4455f99fbd9931c964 to your computer and use it in GitHub Desktop.
Sample task manager to handle recursion with trampoline
This file contains hidden or 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
| /** | |
| * 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); | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.