123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- import { WatchSource } from 'vue'
- export function useLoop(
- loopFunctions: (() => void | Promise<void>)[],
- interval: number | string,
- watchSources: (WatchSource | object)[] = []
- ) {
- let queryLoop: number | null = null
- let querying = false
- let stopFlag = false
- const startQuery = async () => {
- querying = true
- stopFlag = false
- await Promise.allSettled(loopFunctions.map(func => func()))
- if (stopFlag) {
- return
- }
- queryLoop = window.setTimeout(
- startQuery,
- typeof interval === 'string'
- ? LOOP_INTERVAL[interval]
- ? LOOP_INTERVAL[interval]
- : 15 * 1000
- : interval
- )
- }
- const stopQuery = () => {
- stopFlag = true
- if (queryLoop) {
- clearTimeout(queryLoop)
- queryLoop = null
- }
- querying = false
- }
- if (watchSources.length) {
- watch(watchSources, () => {
- stopQuery()
- startQuery()
- })
- }
- onMounted(() => {
- if (querying) {
- return
- }
- startQuery()
- })
- onActivated(() => {
- if (querying) {
- return
- }
- startQuery()
- })
- onDeactivated(() => {
- stopQuery()
- })
- onBeforeUnmount(() => {
- stopQuery()
- })
- }
|