Skip to content

Instantly share code, notes, and snippets.

@libersolis-dev
Last active March 10, 2019 18:39
Show Gist options
  • Save libersolis-dev/93a99386e2681a0853e9c36385b8a7c8 to your computer and use it in GitHub Desktop.
Save libersolis-dev/93a99386e2681a0853e9c36385b8a7c8 to your computer and use it in GitHub Desktop.
React Native timeoutfix.js
import { Platform, InteractionManager } from 'react-native';
const timeoutFix = () => {
const _setTimeout = global.setTimeout;
const _clearTimeout = global.clearTimeout;
const MAX_TIMER_DURATION_MS = 60 * 1000;
if (Platform.OS === 'android') {
const timerFix = {};
const runTask = (id, fn, ttl, args) => {
const waitingTime = ttl - Date.now();
if (waitingTime <= 1) {
InteractionManager.runAfterInteractions(() => {
if (!timerFix[id]) {
return;
}
delete timerFix[id];
fn(...args);
});
return;
}
const afterTime = Math.min(waitingTime, MAX_TIMER_DURATION_MS);
timerFix[id] = _setTimeout(() => runTask(id, fn, ttl, args), afterTime);
};
global.setTimeout = (fn, time, ...args) => {
if (MAX_TIMER_DURATION_MS < time) {
const ttl = Date.now() + time;
const id = '_lt_' + Object.keys(timerFix).length;
runTask(id, fn, ttl, args);
return id;
}
return _setTimeout(fn, time, ...args);
};
global.clearTimeout = (id) => {
if (typeof id === 'string' && id.startWith('_lt_')) {
_clearTimeout(timerFix[id]);
delete timerFix[id];
return;
}
_clearTimeout(id);
};
}
};
export default timeoutFix;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment