useNextFrame.js 819 B

123456789101112131415161718192021222324252627282930
  1. import raf from "rc-util/es/raf";
  2. import * as React from 'react';
  3. export default (function () {
  4. var nextFrameRef = React.useRef(null);
  5. function cancelNextFrame() {
  6. raf.cancel(nextFrameRef.current);
  7. }
  8. function nextFrame(callback) {
  9. var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
  10. cancelNextFrame();
  11. var nextFrameId = raf(function () {
  12. if (delay <= 1) {
  13. callback({
  14. isCanceled: function isCanceled() {
  15. return nextFrameId !== nextFrameRef.current;
  16. }
  17. });
  18. } else {
  19. nextFrame(callback, delay - 1);
  20. }
  21. });
  22. nextFrameRef.current = nextFrameId;
  23. }
  24. React.useEffect(function () {
  25. return function () {
  26. cancelNextFrame();
  27. };
  28. }, []);
  29. return [nextFrame, cancelNextFrame];
  30. });