Skip to content

Instantly share code, notes, and snippets.

@ahmed-musallam
Last active October 25, 2021 13:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ahmed-musallam/3f36751fdfddbb868559cb29eeaa27ad to your computer and use it in GitHub Desktop.
// poll async featch calls in a syncronized fashion, IE do not start the next function call until the previous was resolved.
// also allows for throttling :)
async function poll(fn, onData, throttle) {
const _throttle = throttle || 5000;
let lastPollStarted;
async function _poll(_fn, _onData) {
lastPollStarted = new Date().getTime();
let response = await _fn();
if (response.status === 200) {
// Get and show the message
var stopPolling = onData(response);
if (stopPolling) {
return;
}
const lastPollFinished = new Date().getTime();
const elapsed = lastPollFinished - lastPollStarted;
if (elapsed < _throttle) {
await new Promise(resolve => setTimeout(resolve, _throttle - elapsed));
}
// Call subscribe() again to get the next message
await _poll(_fn, _onData);
}
else {
console.error("Got non-200 response while polling: ", response);
}
}
_poll(fn, onData);
}
// USAGE
async function getGoogle() {
const googleResponse = await fetch("/")
return googleResponse;
}
poll(getGoogle, (response) => console.log(response))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment