JBassx / raf-handler

Use for centralized request animation frame

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

raf-handler

Simple small script to centralize request animation frame.

From an idea of Lorenzo Migliorero

raf-handler

Install

yarn add raf-handler

Usage - Example

import rAF, { subscribeUpdate, unsubscribeUpdate } from "raf-handler"


rAF() // start animationFrameRequest

export default () => {
  const update = timestamp => console.log(timestamp)

  subscribeUpdate(update) // to add your function in a rAF array

  unsubscribeUpdate(update) // to remove your function from a rAF array
}

With react and hooks - Example

import { useMemo, useCallback, useEffect } from "react"
import rAF, { subscribeUpdate, unsubscribeUpdate } from "raf-handler"


export default () => {
  useMemo(rAF, []) // autoinit only one time

  const update = useCallback(timestamp => {
    console.log(timestamp)
  }, [])

  useEffect(() => {
      subscribeUpdate(update) // add your function
    return () => {
      unsubscribeUpdate(update) // remove when unmount
    }
  }, [])

}
  

Other function - Example

Use with an external rAF

import { subscribeUpdate, update as updateRAF } from "raf-handler"


export default () => {
  const update = (timestamp) => console.log(timestamp)

  const initUpdate = timestamp => {
    updateRAF(timestamp)
    id.current = window.requestAnimationFrame(initUpdate)
  }

  subscribeUpdate(update)

  initUpdate()
}

Reset all rAF function

import { resetUpdate } from "raf-handler"

resetUpdate()

Build

yarn build

License

MIT © William Manco

About

Use for centralized request animation frame

License:MIT License


Languages

Language:JavaScript 100.0%