-
Notifications
You must be signed in to change notification settings - Fork 3
/
request.js
44 lines (38 loc) · 950 Bytes
/
request.js
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
var Request = function(ajax_params, opts){
var defaults = {
startTime: null,
ajaxParams: ajax_params,
error: function(){},
ensure: function(){},
timeout: 10*1000,
poll_interval: 1000,
};
$.extend(defaults, opts);
var startTime = (new Date()).getTime();
var completed = false;
if (defaults.ajaxParams.complete){
var original_complete = defaults.ajaxParams.complete;
defaults.ajaxParams.complete = function(xhr, ts){
completed = true;
original_complete(xhr, ts);
}
} else {
defaults.ajaxParams.complete = function(){
completed = true;
}
}
var poll = function(){
if (completed) {
defaults.ensure();
return; // stop polling
}
if (startTime + defaults.timeout < (new Date()).getTime()){ // timeout
defaults.error();
defaults.ensure();
return; // stop polling
}
setTimeout(poll, defaults.poll_interval);
};
$.ajax(defaults.ajaxParams);
poll();
}