Last active
October 25, 2021 13:35
-
-
Save ahmed-musallam/3f36751fdfddbb868559cb29eeaa27ad to your computer and use it in GitHub Desktop.
Revisions
-
ahmed-musallam revised this gist
Feb 20, 2020 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,4 @@ // 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; -
ahmed-musallam created this gist
Feb 20, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal 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))