Skip to content

Instantly share code, notes, and snippets.

@lihuanshuai
Last active March 23, 2016 13:41
Show Gist options
  • Save lihuanshuai/d44fcc6a0d850b5f5c7f to your computer and use it in GitHub Desktop.
Save lihuanshuai/d44fcc6a0d850b5f5c7f to your computer and use it in GitHub Desktop.
function asyncEach(array, fn, progress, finished) {
var i = 0,
maxBurnTime = 100, // ms to run before yielding to user agent
finishedFn = finished || progress,
progressFn = (finishedFn === progress ? null : progress);
function iter() {
var startTime = Date.now();
while(i < array.length) {
fn.call(array, array[i], i++);
if(Date.now() - startTime > maxBurnTime) {
if(progressFn) progressFn(i, array.length);
return window.setTimeout(iter, 0);
}
}
if(progressFn) progressFn(i, array.length);
if(finishedFn) finishedFn(null, array);
}
window.setTimeout(iter, 0);
}
var arr = new Array(1000000);
for (var idx = 0; idx < arr.length; idx++) {
arr[idx] = idx;
}
// async version
var b = 0;
var startTime = new Date();
var endTime;
asyncEach(arr,
function(e) {
b += Math.sqrt(e);
},
null,
// function(done, total) {
// console.log("Summing Square Roots: " + Math.floor( (done/total)* 100 ) + "%");
// },
function(){
endTime = new Date();
console.log('Answer:', b);
console.log('Duration:', endTime - startTime, "ms");
}
);
// sync version
b = 0;
startTime = new Date();
arr.forEach(function(val) { b += Math.sqrt(val); });
endTime = new Date();
console.log('Answer:', b);
console.log('Duration:', endTime - startTime, "ms");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment