lihuanshuai
3/23/2016 - 7:23 AM

async-vs-sync.js

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");