Last active
October 16, 2019 06:03
-
-
Save element6/6c4c6dadbca63b132254a16dcd1f061b to your computer and use it in GitHub Desktop.
safe interval
This file contains hidden or 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
// exception won't break the next run | |
// guarantees at least `waitMs` milliseconds between each run | |
export function safeInterval(fn, waitMs, leading = false) { | |
let _stop = false | |
if (leading) { | |
run() | |
} | |
function run() { | |
try { | |
fn() | |
} catch (err) { | |
// eslint-disable-next-line no-console | |
console.error('safeInterval error', err) | |
} | |
} | |
const runHelper = () => { | |
const timeout = setTimeout(() => { | |
if (_stop) { | |
clearTimeout(timeout) | |
return | |
} | |
run() | |
runHelper() | |
}, waitMs) | |
} | |
runHelper() | |
// return a stopper | |
return () => { | |
_stop = true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment