Skip to content

Instantly share code, notes, and snippets.

@rviscomi
Created September 5, 2012 19:00
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rviscomi/3642608 to your computer and use it in GitHub Desktop.
Save rviscomi/3642608 to your computer and use it in GitHub Desktop.
Timed chunk
/*! 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);
}
@rviscomi
Copy link
Author

rviscomi commented Sep 5, 2012

This function is useful any time you have a potentially long array over which to iterate.

The delay and maxItems parameters were added to support throttling. For example, the Google Maps Geocoding API allows about 10 requests in any given 15 second span of time. By setting delay to 15000ms and maxItems to 10, we can avoid exceeding this limit.

@rviscomi
Copy link
Author

rviscomi commented Sep 5, 2012

@rankinstudio
Copy link

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!

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