docs/.vitepress/theme/components/extrepo/iconQueue.ts

ba4f23d3bab9e2bb3b8efdb22317c8cc8f353ec5
wotaku/docs/.vitepress/theme/components/extrepo/iconQueue.ts history · blame · raw

35 lines · 860 bytes

3 symbols in this file
 1import { MAX_CONCURRENT_DESKTOP, MAX_CONCURRENT_MOBILE } from './constants'
 2
 3let limit = MAX_CONCURRENT_DESKTOP
 4if (typeof window !== 'undefined') {
 5  const mq = window.matchMedia('(max-width: 767px)')
 6  const sync = () => {
 7    limit = mq.matches ? MAX_CONCURRENT_MOBILE : MAX_CONCURRENT_DESKTOP
 8  }
 9  sync()
10  mq.addEventListener('change', sync)
11}
12
13let active = 0
14const queue: (() => Promise<void>)[] = []
15
16function pump() {
17  while (active < limit && queue.length) {
18    const job = queue.shift()!
19    active++
20    job().finally(() => {
21      active--
22      pump()
23    })
24  }
25}
26
27// Returns a cancel fn that drops the job if it hasn't started yet.
28export function scheduleIconLoad(load: () => Promise<void>): () => void {
29  let cancelled = false
30  queue.push(() => cancelled ? Promise.resolve() : load())
31  pump()
32  return () => {
33    cancelled = true
34  }
35}