-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
59 lines (49 loc) · 1.42 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
import { NativeEventEmitter, NativeModules } from "react-native";
const { RNBackgroundTimerAndroid } = NativeModules;
const timerDataMap = {};
let uniqueIdCounter = 0;
if (RNBackgroundTimerAndroid !== null) {
const eventEmitter = new NativeEventEmitter(RNBackgroundTimerAndroid);
eventEmitter.addListener(RNBackgroundTimerAndroid.TIMER_EVENT, id => {
const timerData = timerDataMap[id];
if (timerData) {
const { callback, repeats } = timerData;
if (!repeats) delete timerDataMap[id];
callback();
}
});
}
function setTimer(callback, millis, onError = () => {}, repeats) {
assertAndroid();
const id = ++uniqueIdCounter;
timerDataMap[id] = { callback, repeats };
RNBackgroundTimerAndroid.setTimer(id, millis, repeats).catch(onError);
return id;
}
async function clearTimer(id) {
assertAndroid();
if (timerDataMap[id]) {
delete timerDataMap[id];
await RNBackgroundTimerAndroid.clearTimer(id);
}
}
function assertAndroid() {
if (RNBackgroundTimerAndroid === null) {
throw new Error("Background timer can only be used in Android devices");
}
}
class BackgroundTimer {
static setTimeout(callback, millis, onError) {
return setTimer(callback, millis, onError, false);
}
static setInterval(callback, millis, onError) {
return setTimer(callback, millis, onError, true);
}
static clearTimeout(id) {
return clearTimer(id);
}
static clearInterval(id) {
return clearTimer(id);
}
}
export default BackgroundTimer;