forked from juanamd/react-native-background-timer-android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
49 lines (40 loc) · 1.19 KB
/
index.js
File metadata and controls
49 lines (40 loc) · 1.19 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
import { NativeEventEmitter, NativeModules } from "react-native";
const { RNBackgroundTimerAndroid } = NativeModules;
const eventEmitter = new NativeEventEmitter(RNBackgroundTimerAndroid);
const timerDataMap = {};
let uniqueIdCounter = 0;
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) {
const id = ++uniqueIdCounter;
timerDataMap[id] = { callback, repeats };
RNBackgroundTimerAndroid.setTimer(id, millis, repeats).catch(onError);
return id;
}
async function clearTimer(id) {
if (timerDataMap[id]) {
delete timerDataMap[id];
await RNBackgroundTimerAndroid.clearTimer(id);
}
}
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;