useLock.js 730 B

12345678910111213141516171819202122232425
  1. import { onBeforeUnmount } from 'vue';
  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. let duration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 250;
  10. let lock = null;
  11. let timeout;
  12. onBeforeUnmount(() => {
  13. clearTimeout(timeout);
  14. });
  15. function doLock(locked) {
  16. if (locked || lock === null) {
  17. lock = locked;
  18. }
  19. clearTimeout(timeout);
  20. timeout = setTimeout(() => {
  21. lock = null;
  22. }, duration);
  23. }
  24. return [() => lock, doLock];
  25. }