Created
March 5, 2016 08:23
-
-
Save GeorgeDewar/762ae3500c687c52e0be to your computer and use it in GitHub Desktop.
A technique for keeping the UI thread moving when you need to do a fair bit of processing
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
var loadChain = new LoadChain(); | |
loadChain.push(function(){ | |
console.log("Intensive work is happening here..."); | |
}); | |
loadChain.push(function(){ | |
console.log("And some more is happening here..."); | |
}); | |
loadChain.push(function(){ | |
console.log("And if you have some code to indicate your progess, it'll work!"); | |
}); | |
loadChain.start(); |
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
// A quick and dirty implementation of a queue to prevent the UI thread from being tied up for several seconds, and | |
// (for example) allow a progress bar to work. You can push functions onto the queue, and when you call myQueue.start(), | |
// it will run each function in a chain of window.setTimeout calls. | |
function LoadChain() { | |
this.queue = []; | |
this.push = function(f) { | |
var self = this; | |
// Push a function onto the queue that executes the user-specified function, then sets a timeout to execute the | |
// next function if there is one | |
this.queue.push(function() { | |
f(); | |
var next = self.queue.shift(); | |
if(next) window.setTimeout(next, 0); | |
}); | |
}; | |
this.start = function() { | |
var first = this.queue.shift(); | |
first(); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment