Created
October 12, 2018 13:53
-
-
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 π
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 characters
| 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