代码拉取完成,页面将自动刷新
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();
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。