Skip to content

Instantly share code, notes, and snippets.

@everdimension
Last active April 19, 2019 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save everdimension/ab155280f72d306c12687cc3161b11d9 to your computer and use it in GitHub Desktop.
Save everdimension/ab155280f72d306c12687cc3161b11d9 to your computer and use it in GitHub Desktop.
Polling: "make request — wait for response, but no less than 1 second — make another request"
export function sequentialPolling({
taskFn,
interval = 1000,
}: {
taskFn: () => Promise<any>;
interval?: number;
}) {
let isActive = true;
let timeoutId: number | undefined;
let rejector: Function | undefined;
function poll() {
const timeoutPromise = new Promise((resolve, reject) => {
rejector = reject;
timeoutId = window.setTimeout(resolve, interval);
});
Promise.all([timeoutPromise, taskFn()])
.then(() => {
if (isActive) {
poll();
}
})
.catch((error) => {
if (error === 'cancel') {
// pass
// this just means we've cancelled polling
return;
}
throw error;
});
}
poll();
return () => {
clearTimeout(timeoutId);
isActive = false;
if (rejector) {
rejector('cancel');
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment