Last active
March 10, 2019 18:39
-
-
Save libersolis-dev/93a99386e2681a0853e9c36385b8a7c8 to your computer and use it in GitHub Desktop.
React Native timeoutfix.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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