Ai
11 Star 0 Fork 4

OpenHarmony-SIG/rntpc_react-native-background-timer
关闭

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
index.js 2.62 KB
一键复制 编辑 原始数据 按行查看 历史
import {
DeviceEventEmitter,
NativeAppEventEmitter,
NativeEventEmitter,
NativeModules,
Platform,
TurboModuleRegistry,
} from 'react-native';
const RNBackgroundTimer = TurboModuleRegistry
? TurboModuleRegistry.get('BackgroundTimerTurboModule')
: NativeModules.BackgroundTimer;
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,
harmony: () => 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();
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/openharmony-sig/rntpc_react-native-background-timer.git
git@gitee.com:openharmony-sig/rntpc_react-native-background-timer.git
openharmony-sig
rntpc_react-native-background-timer
rntpc_react-native-background-timer
master

搜索帮助