2161f6b9e3ae34838676f7f0078cf614eb39c0fd
[lhc/web/wiklou.git] / resources / lib / jquery.async.js
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
11 // opts.delay : (default 10) delay between async call in ms
12 // opts.bulk : (default 500) delay during which the loop can continue synchronously without yielding the CPU
13 // opts.test : (default true) function to test in the while test part
14 // opts.loop : (default empty) function to call in the while loop part
15 // opts.end : (default empty) function to call at the end of the while loop
16 $.whileAsync = function(opts) {
17 var delay = Math.abs(opts.delay) || 10,
18 bulk = isNaN(opts.bulk) ? 500 : Math.abs(opts.bulk),
19 test = opts.test || function(){ return true; },
20 loop = opts.loop || function(){},
21 end = opts.end || function(){};
22
23 (function(){
24
25 var t = false,
26 begin = new Date();
27
28 while( t = test() ) {
29 loop();
30 if( bulk === 0 || (new Date() - begin) > bulk ) {
31 break;
32 }
33 }
34 if( t ) {
35 setTimeout(arguments.callee, delay);
36 }
37 else {
38 end();
39 }
40
41 })();
42 };
43
44 // opts.delay : (default 10) delay between async call in ms
45 // opts.bulk : (default 500) delay during which the loop can continue synchronously without yielding the CPU
46 // opts.loop : (default empty) function to call in the each loop part, signature: function(index, value) this = value
47 // opts.end : (default empty) function to call at the end of the each loop
48 $.eachAsync = function(array, opts) {
49 var i = 0,
50 l = array.length,
51 loop = opts.loop || function(){};
52
53 $.whileAsync(
54 $.extend(opts, {
55 test: function() { return i < l; },
56 loop: function() {
57 var val = array[i];
58 return loop.call(val, i++, val);
59 }
60 })
61 );
62 };
63
64 $.fn.eachAsync = function(opts) {
65 $.eachAsync(this, opts);
66 return this;
67 }
68
69 })(jQuery);