Skip to content

Instantly share code, notes, and snippets.

@ExcitedSpider
Last active November 30, 2020 08:36
Show Gist options
  • Save ExcitedSpider/83c487c8e3a50b7faee0bf76303bedd9 to your computer and use it in GitHub Desktop.
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
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