watchPolling.ts 720 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { watch } from "vue";
  2. export const watchPolling = <T>(
  3. getStart: () => { start: boolean; payload: T },
  4. task: (payload: T) => void
  5. ) => {
  6. let timeout: number;
  7. let stop = false;
  8. const cleanup = () => {
  9. clearTimeout(timeout);
  10. stop = true;
  11. };
  12. const stopWatch = watch(
  13. getStart,
  14. ({ start, payload }, _, onCleanup) => {
  15. if (!start) {
  16. return;
  17. }
  18. stop = false;
  19. const pollingTask = async () => {
  20. await task(payload);
  21. if (!stop) {
  22. timeout = setTimeout(pollingTask, 3000);
  23. }
  24. };
  25. pollingTask();
  26. onCleanup(cleanup);
  27. },
  28. { immediate: true }
  29. );
  30. return () => {
  31. cleanup();
  32. stopWatch();
  33. };
  34. };