forked from artem-russkikh/react-native-clock-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
66 lines (58 loc) · 1.71 KB
/
index.js
File metadata and controls
66 lines (58 loc) · 1.71 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
var clockSync = function (config) {
this.client = require('react-native-ntp-client');
if (!config) {
config = {};
}
this.ntpServers = config.servers || [{
server: this.client.defaultNtpServer,
port: this.client.defaultNtpPort
}];
this.currentIndex = 0;
this.currentServer = this.ntpServers[this.currentIndex];
this.tickRate = config.syncDelay || 300;
this.tickRate = this.tickRate * 1000;
this.delta = [];
this.limit = config.history || 10;
this.syncTime();
this.startTick();
};
clockSync.prototype.shiftServer = function () {
if (this.ntpServers[this.currentIndex + 1]) {
this.currentIndex++;
this.currentServer = this.ntpServers[this.currentIndex];
}
};
clockSync.prototype.startTick = function () {
setInterval(function () {
this.getDelta();
}.bind(this), this.tickRate);
};
clockSync.prototype.getTime = function () {
var sum = this.delta.reduce(function (a, b) {
return a + b;
}, 0);
var avg = Math.round(sum / this.delta.length) || 0;
return ((new Date()).getTime() + avg);
};
clockSync.prototype.syncTime = function () {
this.getDelta();
};
clockSync.prototype.getDelta = function (callback) {
this.client.getNetworkTime(this.currentServer.server, this.currentServer.port, function (err, date) {
if (err) {
console.log('Shifting to backup server');
this.shiftServer();
} else {
var tempServerTime = date.getTime();
var tempLocalTime = (new Date()).getTime();
if (this.delta.length === this.limit) {
this.delta.shift();
}
this.delta.push(tempServerTime - tempLocalTime);
if (callback) {
callback(tempServerTime - tempLocalTime)
}
}
}.bind(this))
};
module.exports = clockSync;