Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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