import { sleep } from "./sleep" import { toMs } from "../../time/funcs/toMs" /** * 等待条件判断 * 提供一个函数,会每隔一段时间执行它,当判断为真时,返回 * * @example * await when(()=>window.isOk == true) * * @param ms 毫秒,可接受时间文本 * @param timeout 超时时间,超时后会返回错误,0 为不限制 */ export async function when(tryFunc: () => boolean, ms: string | number = 50, timeout?: string | number) { ms = toMs(ms) if (timeout != undefined) timeout = toMs(timeout) return new Promise(async function (resolve, reject) { let hasTimeout = timeout && timeout > 0 let t0!: number if (hasTimeout) t0 = performance.now() while (!tryFunc()) { if (hasTimeout) { let tCost = performance.now() - t0 if (tCost >= timeout) { resolve() return } } await sleep(ms) } resolve() }) } export async function whenAsync(tryFunc: () => Promise, ms: string | number = 50, timeout?: string | number) { ms = toMs(ms) if (timeout != undefined) timeout = toMs(timeout) return new Promise(async function (resolve, reject) { let hasTimeout = timeout && timeout > 0 let t0!: number if (hasTimeout) t0 = performance.now() while (!(await tryFunc())) { if (hasTimeout) { let tCost = performance.now() - t0 if (tCost >= timeout) { resolve() return } } await sleep(ms) } resolve() }) }