raf-plus
raf-plus is used to manage window.requestAnimationFrame, which will only invokes the passed function at most once per animation frame.
Reason
The window.requestAnimationFrame method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.
-- MDN
However, it does not manage the queue. For example:
const heavyAnimation = () => {
}
document.addEventListener('scroll', e => requestAnimation(heavyAnimation), false)
The scroll event may fire more than once within one frame, so the heavyAnimation function may be called more than once before next repaint, but repetitively call heavyAnimation at one animation frame is unnecessary and waste of resources!!!
The raf-plus help you manage requestAnimation's queue by ignoring the duplicate callback function in same animation frame. For comparison:
const { raf } from 'raf-plus'
const animation = () => console.log('animation')
window.requestAnimationFrame(animation)
window.requestAnimationFrame(animation)
raf(animation)
raf(animation)
Install
$ npm install --save raf-plus
or
$ yarn add raf-plus
Usage
The raf-plus only exports two methods
requestAnimationFrame(callback)
The same as requestAnimationFrame, but it will not return request id.
const { requestAnimationFrame } from 'raf-plus'
const animation = timeStamp => {
}
requestAnimationFrame(animation)
cancelAnimationFrame(callback)
The same as cancelAnimationFrame, but it uses the function passed to requestAnimationFrame as parameter.
const { requestAnimationFrame, cancelAnimationFrame } from 'raf-plus'
const animation = timeStamp => {
}
requestAnimationFrame(animation)
cancelAnimationFrame(animation)
Contributing
- ⇄ Pull requests and ★ Stars are always welcome.
- For bugs and feature requests, please create an issue.
Licence
MIT