Skip to content

Instantly share code, notes, and snippets.

@element6
Last active October 16, 2019 06:03
Show Gist options
  • Save element6/6c4c6dadbca63b132254a16dcd1f061b to your computer and use it in GitHub Desktop.
Save element6/6c4c6dadbca63b132254a16dcd1f061b to your computer and use it in GitHub Desktop.
safe interval
// 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