main
Last change
on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago |
Update repo after prototype presentation
|
-
Property mode
set to
100644
|
File size:
1.3 KB
|
Rev | Line | |
---|
[d565449] | 1 | import { useCallback, useEffect, useMemo, useRef } from 'react';
|
---|
| 2 | export default function useRafLoop(callback, initiallyActive) {
|
---|
| 3 | if (initiallyActive === void 0) { initiallyActive = true; }
|
---|
| 4 | var raf = useRef(null);
|
---|
| 5 | var rafActivity = useRef(false);
|
---|
| 6 | var rafCallback = useRef(callback);
|
---|
| 7 | rafCallback.current = callback;
|
---|
| 8 | var step = useCallback(function (time) {
|
---|
| 9 | if (rafActivity.current) {
|
---|
| 10 | rafCallback.current(time);
|
---|
| 11 | raf.current = requestAnimationFrame(step);
|
---|
| 12 | }
|
---|
| 13 | }, []);
|
---|
| 14 | var result = useMemo(function () {
|
---|
| 15 | return [
|
---|
| 16 | function () {
|
---|
| 17 | // stop
|
---|
| 18 | if (rafActivity.current) {
|
---|
| 19 | rafActivity.current = false;
|
---|
| 20 | raf.current && cancelAnimationFrame(raf.current);
|
---|
| 21 | }
|
---|
| 22 | },
|
---|
| 23 | function () {
|
---|
| 24 | // start
|
---|
| 25 | if (!rafActivity.current) {
|
---|
| 26 | rafActivity.current = true;
|
---|
| 27 | raf.current = requestAnimationFrame(step);
|
---|
| 28 | }
|
---|
| 29 | },
|
---|
| 30 | function () { return rafActivity.current; },
|
---|
| 31 | ];
|
---|
| 32 | }, []);
|
---|
| 33 | useEffect(function () {
|
---|
| 34 | if (initiallyActive) {
|
---|
| 35 | result[1]();
|
---|
| 36 | }
|
---|
| 37 | return result[0];
|
---|
| 38 | // eslint-disable-next-line react-hooks/exhaustive-deps
|
---|
| 39 | }, []);
|
---|
| 40 | return result;
|
---|
| 41 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.