|
| 1 | +import { ref, isRef, watch, onMounted, onUnmounted, Ref } from '../../api' |
| 2 | + |
| 3 | +type TFps = number | Ref<number> |
| 4 | + |
| 5 | +const getFps = (fps: TFps) => (isRef(fps) ? fps.value : fps) |
| 6 | +const calcFpsInterval = (fps: number) => 1000 / fps |
| 7 | + |
| 8 | +export function useRafFn( |
| 9 | + callback: Function, |
| 10 | + fps: TFps = 60, |
| 11 | + runOnMount = true |
| 12 | +) { |
| 13 | + const isRunningRef = ref(false) |
| 14 | + const fpsIntervalRef = ref(calcFpsInterval(getFps(fps))) |
| 15 | + let startTime = 0 |
| 16 | + let timeNow = 0 |
| 17 | + let isPaused = false |
| 18 | + let prevTime = 0 |
| 19 | + let timeLast = 0 |
| 20 | + function loop(timeStamp: number) { |
| 21 | + if (!startTime) startTime = timeStamp |
| 22 | + if (!isRunningRef.value) return |
| 23 | + |
| 24 | + if (!isPaused) { |
| 25 | + timeNow = timeStamp - startTime - prevTime |
| 26 | + } else { |
| 27 | + prevTime = timeStamp - startTime - timeNow |
| 28 | + timeNow = timeStamp - startTime - prevTime |
| 29 | + isPaused = false |
| 30 | + } |
| 31 | + |
| 32 | + // Run callback only on the given fps |
| 33 | + if (Math.ceil(timeNow - timeLast) > fpsIntervalRef.value) { |
| 34 | + callback(timeNow) |
| 35 | + timeLast = timeNow |
| 36 | + } |
| 37 | + |
| 38 | + requestAnimationFrame(loop) |
| 39 | + } |
| 40 | + |
| 41 | + const start = () => { |
| 42 | + isRunningRef.value = true |
| 43 | + requestAnimationFrame(loop) |
| 44 | + } |
| 45 | + |
| 46 | + const stop = () => { |
| 47 | + isRunningRef.value = false |
| 48 | + isPaused = true |
| 49 | + } |
| 50 | + |
| 51 | + // Watch fps value since it could potentially be a ref and we may want |
| 52 | + // to change the Raf speed from user's input |
| 53 | + const updateFpsInterval = () => { |
| 54 | + // If fps is not a ref there is no point in updating it |
| 55 | + if (!isRef(fps)) return |
| 56 | + watch(fps, () => { |
| 57 | + fpsIntervalRef.value = calcFpsInterval(getFps(fps)) |
| 58 | + }) |
| 59 | + } |
| 60 | + updateFpsInterval() |
| 61 | + |
| 62 | + onMounted(() => runOnMount && start()) |
| 63 | + onUnmounted(stop) |
| 64 | + |
| 65 | + return { |
| 66 | + isRunning: isRunningRef, |
| 67 | + start, |
| 68 | + stop |
| 69 | + } |
| 70 | +} |
0 commit comments