Skip to content

Instantly share code, notes, and snippets.

@OutThisLife
Last active April 18, 2018 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OutThisLife/0ad8671e371c2bf90cc133e1714e3d77 to your computer and use it in GitHub Desktop.
Save OutThisLife/0ad8671e371c2bf90cc133e1714e3d77 to your computer and use it in GitHub Desktop.
singleton raf loop
// @flow
export const renders: Array<Function> = []
let animId: AnimationFrameID
export default ((): void => {
if (typeof window === 'undefined') {
return
}
const stop = () => window.cancelAnimationFrame(animId)
const draw = () =>
(animId = window.requestAnimationFrame(() => {
draw()
for (let i = 0, l = renders.length; i < l; i++) {
renders[i].call(renders[i])
}
}))
if (!animId) {
renders.push = function() {
Array.prototype.push.apply(this, arguments)
stop()
draw()
}
document.addEventListener('visibilitychange', () => (document.hidden ? stop() : draw()), false)
}
})()
// @flow
import { lifecycle } from 'recompose'
import { renders } from 'raf'
export default lifecycle({
animId: number
componentDidMount () {
this.animId = renders.push(() => {
// do things
})
}
componentWillUnmount () {
renders.splice(this.animId, 1)
}
})(() => <div />)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment