Files
FrenoCorp/node_modules/viem/utils/poll.ts
Michael Freno 7c684a42cc FRE-600: Fix code review blockers
- Consolidated duplicate UndoManagers to single instance
- Fixed connection promise to only resolve on 'connected' status
- Fixed WebSocketProvider import (WebsocketProvider)
- Added proper doc.destroy() cleanup
- Renamed isPresenceInitialized property to avoid conflict

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-04-25 00:08:01 -04:00

46 lines
1.1 KiB
TypeScript

import type { ErrorType } from '../errors/utils.js'
import { wait } from './wait.js'
type PollOptions<data> = {
// Whether or not to emit when the polling starts.
emitOnBegin?: boolean | undefined
// The initial wait time (in ms) before polling.
initialWaitTime?: ((data: data | void) => Promise<number>) | undefined
// The interval (in ms).
interval: number
}
export type PollErrorType = ErrorType
/**
* @description Polls a function at a specified interval.
*/
export function poll<data>(
fn: ({ unpoll }: { unpoll: () => void }) => Promise<data | void>,
{ emitOnBegin, initialWaitTime, interval }: PollOptions<data>,
) {
let active = true
const unwatch = () => (active = false)
const watch = async () => {
let data: data | undefined | void
if (emitOnBegin) data = await fn({ unpoll: unwatch })
const initialWait = (await initialWaitTime?.(data)) ?? interval
await wait(initialWait)
const poll = async () => {
if (!active) return
await fn({ unpoll: unwatch })
await wait(interval)
poll()
}
poll()
}
watch()
return unwatch
}