Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Created December 3, 2020 21:05
Show Gist options
  • Save Oaphi/c3f96f193a6eae8a243c0ff8a7aed67b to your computer and use it in GitHub Desktop.
Save Oaphi/c3f96f193a6eae8a243c0ff8a7aed67b to your computer and use it in GitHub Desktop.
Promise-based interval runner (cancellable)
const withInterval = async ({
timeouts = [],
delay = 0,
interval = 4,
callback,
times = 1,
stopIf = () => false
}) => {
if (!times) {
return;
}
if (delay) {
await new Promise((res) => setTimeout(res, delay));
}
if (typeof callback !== "function") { return; }
const result = await callback();
if (stopIf(result)) {
return result;
}
return new Promise((res, rej) => {
const timesLeft = times - 1;
const newId = setTimeout(
() => withInterval({
timeouts,
delay,
interval,
callback,
times: timesLeft,
stopIf
}).then((output) => {
timeouts.splice(timeouts.indexOf(newId), 1);
res(output);
}).catch(rej),
interval);
timeouts.push(newId);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment