useTimeout.ts 945 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { ref, watch } from 'vue';
  2. import { tryOnUnmounted } from '@vueuse/core';
  3. import { isFunction } from '/@/utils/is';
  4. export function useTimeoutFn(handle: Fn<any>, wait: number, native = false) {
  5. if (!isFunction(handle)) {
  6. throw new Error('handle is not Function!');
  7. }
  8. const { readyRef, stop, start } = useTimeoutRef(wait);
  9. if (native) {
  10. handle();
  11. } else {
  12. watch(
  13. readyRef,
  14. (maturity) => {
  15. maturity && handle();
  16. },
  17. { immediate: false }
  18. );
  19. }
  20. return { readyRef, stop, start };
  21. }
  22. export function useTimeoutRef(wait: number) {
  23. const readyRef = ref(false);
  24. let timer: TimeoutHandle;
  25. function stop(): void {
  26. readyRef.value = false;
  27. timer && window.clearTimeout(timer);
  28. }
  29. function start(): void {
  30. stop();
  31. timer = setTimeout(() => {
  32. readyRef.value = true;
  33. }, wait);
  34. }
  35. start();
  36. tryOnUnmounted(stop);
  37. return { readyRef, stop, start };
  38. }