Last active
November 30, 2020 08:36
-
-
Save ExcitedSpider/83c487c8e3a50b7faee0bf76303bedd9 to your computer and use it in GitHub Desktop.
Util polling method. Use `requestIdleCallback` first. If user agent not support (e.g. safari, ie), use `setInterval` instead
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
const DEFAULT_POLLING_INTERVAL = 300 | |
interface Polling { | |
(cb: () => void, timeout?: number): { | |
/** stop polling */ | |
stopPolling: () => void | |
} | |
} | |
/** | |
* polling method | |
* | |
* Use `requestIdleCallback` first. If user agent not support (e.g. safari, ie), use `setInterval` instead | |
* Can I use: https://caniuse.com/?search=requestIdleCallback | |
* | |
* @param cb polling callback | |
* @param pollingInterval polling interval in milliseconds | |
* @return stopPolling to stop polling | |
* | |
* @example | |
* const { stopPolling } = polling(()=>console.log('hello world for every 300 ms'), 300) | |
* | |
* // in some condition | |
* stopPolling() | |
*/ | |
const polling: Polling = (cb, pollingInterval = DEFAULT_POLLING_INTERVAL) => { | |
const ricAvaliable = !!(window as any).requestIdleCallback | |
if (ricAvaliable) { | |
let stopFlag = false | |
const pollingmethodUsingRic = (cb: () => void) => { | |
;(window as any).requestIdleCallback( | |
() => { | |
cb() | |
window.setTimeout(() => { | |
if (!stopFlag) { | |
pollingmethodUsingRic(cb) | |
} | |
}, pollingInterval) | |
}, | |
{ | |
pollingInterval, | |
}, | |
) | |
return { | |
stopPolling: () => { | |
stopFlag = true | |
}, | |
} | |
} | |
return pollingmethodUsingRic(cb) | |
} | |
const timerId = window.setInterval(cb, pollingInterval) | |
return { | |
stopPolling: () => { | |
window.clearInterval(timerId) | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment