-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathJQuery.doWhen.js
More file actions
113 lines (88 loc) · 2.82 KB
/
JQuery.doWhen.js
File metadata and controls
113 lines (88 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*! Copyright (c) 2014 - Paul Tavares - purtuga - @paul_tavares - MIT License */
;(function($){
/**
* Delays the execution of a function until an expression returns true.
* The expression is checked every 100 milliseconds for as many tries
* as defined in in the attempts option
*
* @param {Object} options
* @param {Function} options.when
* Function to execute on every interval.
* Must return true (boolean) in order for
* options.do to be executed.
* @param {Function} [options.exec]
* Function to be executed once options.when()
* returns true.
* @param {Interger} [options.interval=100]
* How long to wait in-between tries.
* @param {Interger} [options.attempts=100]
* How many tries to use before its considered
* a failure.
* @param {Interger} [options.delayed=0]
* Number of miliseconds to wait before execution
is started. Default is imediately.
*
* @return {jQuery.Promise}
*
* @example
*
* $.doWhen({
* when: function(){
* return false;
* },
* exec: function(){
* alert("never called given false response on when param!");
* }
* })
* .fail(function(){
* alert('ALERT: FAILED CONDITION');
* })
* .then(function(){
* alert("resolved.");
* });
*
*/
$.doWhen = function(options) {
return $.Deferred(function(dfd){
var opt = $.extend({}, {
when: null,
exec: function(){},
interval: 100,
attempts: 100,
delayed: 0
},
options,
{
checkId: null
}),
startChecking = function(){
// Check condition now and if true, then resolve object
if (opt.when() === true) {
opt.exec.call(dfd.promise());
dfd.resolve();
return;
}
// apply minimal UI and hide the overlay
opt.checkId = setInterval(function(){
if (opt.attempts === 0) {
clearInterval(opt.checkId);
dfd.reject();
} else {
--opt.attempts;
if (opt.when() === true) {
opt.attempts = 0;
clearInterval(opt.checkId);
opt.exec.call(dfd.promise());
dfd.resolve();
}
}
}, opt.interval);
};
if (opt.delayed > 0) {
setTimeout(startChecking, Number(opt.delayed));
} else {
startChecking();
}
}).promise();
};
})(jQuery);