Last active
April 18, 2018 20:43
-
-
Save OutThisLife/0ad8671e371c2bf90cc133e1714e3d77 to your computer and use it in GitHub Desktop.
singleton raf loop
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
// @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) | |
} | |
})() |
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
// @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