Skip to content

Instantly share code, notes, and snippets.

@ahmed-musallam
Last active October 25, 2021 13:35
Show Gist options
  • Save ahmed-musallam/3f36751fdfddbb868559cb29eeaa27ad to your computer and use it in GitHub Desktop.
Save ahmed-musallam/3f36751fdfddbb868559cb29eeaa27ad to your computer and use it in GitHub Desktop.

Revisions

  1. ahmed-musallam revised this gist Feb 20, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion poll.js
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    // poll async functions in a syncronized fashion, IE do not start the next function call until the previous was resolved.
    // 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;
  2. ahmed-musallam created this gist Feb 20, 2020.
    37 changes: 37 additions & 0 deletions poll.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    // poll async functions 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))