export async function yieldToEventLoop() {
    await sleep(0);
}
export async function yieldEvery(index, interval = 8) {
    if (index > 0 && index % interval === 0)
        await yieldToEventLoop();
}
export function scheduleBackground(callback, delayMs = 0, signal) {
    let abort = () => { };
    const timer = setTimeout(() => {
        signal?.removeEventListener('abort', abort);
        if (!signal?.aborted)
            callback();
    }, Math.max(0, delayMs));
    abort = () => clearTimeout(timer);
    if (signal?.aborted)
        clearTimeout(timer);
    else
        signal?.addEventListener('abort', abort, { once: true });
    timer.unref?.();
    return timer;
}
export async function sleep(delayMs, options = {}) {
    if (options.signal?.aborted)
        return;
    await new Promise((resolve) => {
        let timer;
        const done = () => {
            if (timer)
                clearTimeout(timer);
            options.signal?.removeEventListener('abort', done);
            resolve();
        };
        timer = setTimeout(done, Math.max(0, delayMs));
        options.signal?.addEventListener('abort', done, { once: true });
        timer.unref?.();
    });
}
