Posted By

kayue on 12/31/10


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

hobbyman


Process large array


 / Published in: JavaScript
 

  1. // http://blogs.sitepoint.com/2010/12/08/javascript-large-data-processing/
  2.  
  3. function ProcessArray(data, handler, callback) {
  4. var maxtime = 100; // chunk processing time
  5. var delay = 20; // delay between processes
  6. var queue = data.concat(); // clone original array
  7. setTimeout(function() {
  8. var endtime = +new Date() + maxtime;
  9. do {
  10. handler(queue.shift());
  11. } while (queue.length > 0 && endtime > +new Date());
  12.  
  13. // all done or time is up
  14. if (queue.length > 0) {
  15. // create another thread
  16. setTimeout(arguments.callee, delay);
  17. } else {
  18. if (callback) callback();
  19. }
  20. }, delay);
  21. }
  22. // end of ProcessArray function
  23.  
  24. // process an individual data item
  25. function Process(dataitem) {
  26. // console.log(dataitem);
  27. $("#hello").text(dataitem);
  28. }
  29. // processing is complete
  30. function Done() {
  31. $("#hello").text("done");
  32. }
  33. // test data
  34. var data = [];
  35. for (var i = 0; i < 50000; i++) data[i] = i;
  36. // process all items
  37. ProcessArray(data, Process, Done);
  38.  
  39. ​

Report this snippet  

You need to login to post a comment.