-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
33 lines (29 loc) · 1023 Bytes
/
index.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
const DEFAULT_URL = window.location.origin;
const DEFAULT_TIMEOUT = 10000;
const DEFAULT_METHOD = 'HEAD';
module.exports = function getOriginTime(options = {}) {
let {url, method, timeout} = options;
url = url || DEFAULT_URL;
method = method || DEFAULT_METHOD;
timeout = timeout || DEFAULT_TIMEOUT;
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
let timeoutId;
if (timeout > 0) {
timeoutId = setTimeout(function() {
reject(new Error(`Timed out after ${timeout}ms trying to get time from ${url}`));
}, timeout);
}
request.onload = function() {
const time = this.getResponseHeader('Date');
timeoutId && clearTimeout(timeoutId);
resolve(time);
};
request.onerror = function(err) {
timeoutId && clearTimeout(timeoutId);
reject(err);
};
request.open(method, url);
request.send();
});
};