-
Notifications
You must be signed in to change notification settings - Fork 230
/
index.js
107 lines (94 loc) · 2.46 KB
/
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
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
import {
DeviceEventEmitter,
NativeAppEventEmitter,
NativeEventEmitter,
NativeModules,
Platform,
} from 'react-native';
const { RNBackgroundTimer } = NativeModules;
const Emitter = new NativeEventEmitter(RNBackgroundTimer);
class BackgroundTimer {
constructor() {
this.uniqueId = 0;
this.callbacks = {};
Emitter.addListener('backgroundTimer.timeout', (id) => {
if (this.callbacks[id]) {
const callbackById = this.callbacks[id];
const { callback } = callbackById;
if (!this.callbacks[id].interval) {
delete this.callbacks[id];
} else {
RNBackgroundTimer.setTimeout(id, this.callbacks[id].timeout);
}
callback();
}
});
}
// Original API
start(delay = 0) {
return RNBackgroundTimer.start(delay);
}
stop() {
return RNBackgroundTimer.stop();
}
runBackgroundTimer(callback, delay) {
const EventEmitter = Platform.select({
ios: () => NativeAppEventEmitter,
android: () => DeviceEventEmitter,
})();
this.start(0);
this.backgroundListener = EventEmitter.addListener(
'backgroundTimer',
() => {
this.backgroundListener.remove();
this.backgroundClockMethod(callback, delay);
},
);
}
backgroundClockMethod(callback, delay) {
this.backgroundTimer = this.setTimeout(() => {
callback();
this.backgroundClockMethod(callback, delay);
}, delay);
}
stopBackgroundTimer() {
this.stop();
this.clearTimeout(this.backgroundTimer);
}
// New API, allowing for multiple timers
setTimeout(callback, timeout) {
this.uniqueId += 1;
const timeoutId = this.uniqueId;
this.callbacks[timeoutId] = {
callback,
interval: false,
timeout,
};
RNBackgroundTimer.setTimeout(timeoutId, timeout);
return timeoutId;
}
clearTimeout(timeoutId) {
if (this.callbacks[timeoutId]) {
delete this.callbacks[timeoutId];
// RNBackgroundTimer.clearTimeout(timeoutId);
}
}
setInterval(callback, timeout) {
this.uniqueId += 1;
const intervalId = this.uniqueId;
this.callbacks[intervalId] = {
callback,
interval: true,
timeout,
};
RNBackgroundTimer.setTimeout(intervalId, timeout);
return intervalId;
}
clearInterval(intervalId) {
if (this.callbacks[intervalId]) {
delete this.callbacks[intervalId];
// RNBackgroundTimer.clearTimeout(intervalId);
}
}
}
export default new BackgroundTimer();