jquery.async.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * jQuery Asynchronous Plugin 1.0
  3. *
  4. * Copyright (c) 2008 Vincent Robert (genezys.net)
  5. * Dual licensed under the MIT (MIT-LICENSE.txt)
  6. * and GPL (GPL-LICENSE.txt) licenses.
  7. *
  8. */
  9. (function($){
  10. // opts.delay : (default 10) delay between async call in ms
  11. // opts.bulk : (default 500) delay during which the loop can continue synchronously without yielding the CPU
  12. // opts.test : (default true) function to test in the while test part
  13. // opts.loop : (default empty) function to call in the while loop part
  14. // opts.end : (default empty) function to call at the end of the while loop
  15. $.whileAsync = function(opts) {
  16. var delay = Math.abs(opts.delay) || 10,
  17. bulk = isNaN(opts.bulk) ? 500 : Math.abs(opts.bulk),
  18. test = opts.test || function(){ return true; },
  19. loop = opts.loop || function(){},
  20. end = opts.end || function(){};
  21. (function(){
  22. var t = false,
  23. begin = new Date();
  24. while( t = test() ) {
  25. loop();
  26. if( bulk === 0 || (new Date() - begin) > bulk ) {
  27. break;
  28. }
  29. }
  30. if( t ) {
  31. setTimeout(arguments.callee, delay);
  32. }
  33. else {
  34. end();
  35. }
  36. })();
  37. };
  38. // opts.delay : (default 10) delay between async call in ms
  39. // opts.bulk : (default 500) delay during which the loop can continue synchronously without yielding the CPU
  40. // opts.loop : (default empty) function to call in the each loop part, signature: function(index, value) this = value
  41. // opts.end : (default empty) function to call at the end of the each loop
  42. $.eachAsync = function(array, opts) {
  43. var i = 0,
  44. l = array.length,
  45. loop = opts.loop || function(){};
  46. $.whileAsync(
  47. $.extend(opts, {
  48. test: function() { return i < l; },
  49. loop: function() {
  50. var val = array[i];
  51. return loop.call(val, i++, val);
  52. }
  53. })
  54. );
  55. };
  56. $.fn.eachAsync = function(opts) {
  57. $.eachAsync(this, opts);
  58. return this;
  59. }
  60. })(jQuery);