Skip to content

Instantly share code, notes, and snippets.

@brenttimmermans
Created October 12, 2018 13:53
Show Gist options
  • Select an option

  • Save brenttimmermans/6a85f69d1899709b41b4f4bae39b4c7f to your computer and use it in GitHub Desktop.

Select an option

Save brenttimmermans/6a85f69d1899709b41b4f4bae39b4c7f to your computer and use it in GitHub Desktop.
Wrapper for calling a functions with fixed interval. Useful for refreshing state of a React component πŸ‘
import randomInt from 'random-int'
const REFRESH_INTERVAL = 2 * 60 * 1000 // ms
const REFRESH_TIME_OUT = 30 * 1000 // ms
export function refresh (refreshFn, interval = REFRESH_INTERVAL) {
let intervalToken
refreshFn()
const timeout = randomInt(REFRESH_TIME_OUT)
const timeoutToken = setTimeout(() => {
intervalToken = setInterval(refreshFn, interval)
}, timeout)
return { timeoutToken, intervalToken }
}
export function stopRefresh (tokens) {
const { timeoutToken, intervalToken } = tokens
clearInterval(intervalToken)
clearTimeout(timeoutToken)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment