Created
September 5, 2012 19:00
-
-
Save rviscomi/3642608 to your computer and use it in GitHub Desktop.
Timed chunk
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
/*! Copyright 2009 Nicholas C. Zakas. All rights reserved. MIT Licensed */ | |
/** | |
* Processes each item in "items" at most 50ms at a time with a sleep of 25ms. | |
* By limiting the amount of time spent in a loop, there is no lock on the UI thread. | |
* | |
* Calls "process" in "context" for each item in "items". | |
* After each item has been processed, "callback" is called with the original array. | |
* | |
* Some modifications to Zakas's code: | |
* * added delay parameter to control how long to sleep | |
* * added maxItems parameter to control the number of items looped at a time | |
* * syntax tweaks and minor optimizations | |
*/ | |
function timedChunk(items, process, context, callback, delay, maxItems) { | |
var n = items.length, | |
delay = delay || 25, | |
maxItems = maxItems || n, | |
i = 0; | |
setTimeout(function chunkTimer(){ | |
var start = +new Date(), | |
j = i; | |
while (i < n && (i - j) < maxItems && (new Date() - start < 50)) { | |
process.call(context, items[i]); | |
i += 1; | |
} | |
if (i < n) { | |
setTimeout(chunkTimer, delay); | |
} | |
else { | |
callback(items); | |
} | |
}, 25); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would you be willing to explain how to use this for a more novice JS user? I'm confused about what the process, callback, and context, are doing? Could you show an example of how this works?
Thanks!