useLock.js 952 B

1234567891011121314151617181920212223242526272829303132
  1. import * as React from 'react';
  2. /**
  3. * Locker return cached mark.
  4. * If set to `true`, will return `true` in a short time even if set `false`.
  5. * If set to `false` and then set to `true`, will change to `true`.
  6. * And after time duration, it will back to `null` automatically.
  7. */
  8. export default function useLock() {
  9. var duration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 250;
  10. var lockRef = React.useRef(null);
  11. var timeoutRef = React.useRef(null);
  12. // Clean up
  13. React.useEffect(function () {
  14. return function () {
  15. window.clearTimeout(timeoutRef.current);
  16. };
  17. }, []);
  18. function doLock(locked) {
  19. if (locked || lockRef.current === null) {
  20. lockRef.current = locked;
  21. }
  22. window.clearTimeout(timeoutRef.current);
  23. timeoutRef.current = window.setTimeout(function () {
  24. lockRef.current = null;
  25. }, duration);
  26. }
  27. return [function () {
  28. return lockRef.current;
  29. }, doLock];
  30. }