Last active
April 19, 2019 13:39
-
-
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"
This file contains 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
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