react-native-background-timer
react-native-background-timer copied to clipboard
Improve timer to avoid drift (use date based correction)
Hey @ocetnik - I'm looking into the idea of implementing a PR for your lib that would implement a Date based timer to avoid drift (instead of relying on the native setTimeout)
If I work on this would you be interested in merging it in or should I just plan on running off a fork? That will change how I approach the issue.
Something like.. (pseudocode, non es-6, non finalized, but this is the idea)...
We use step as the intermediate function to avoid that drift and correction behavior
var interval = 1000; // ms
var expected = Date.now() + interval;
setTimeout(step, interval);
function step() {
var dt = Date.now() - expected; // the drift (positive for overshooting)
if (dt > interval) {
// something really bad happened. Maybe the browser (tab) was inactive?
// possibly special handling to avoid futile "catch up" run
}
… // do what is to be done
expected += interval;
setTimeout(step, Math.max(0, interval - dt)); // take into account drift
}