UNPKG

@jbrowse/core

Version:

JBrowse 2 core libraries used by plugins

91 lines (90 loc) 2.41 kB
import { isWebWorker } from "./isWebWorker.js"; export function createStopTokenChecker(stopToken) { return { time: Date.now(), iters: 0, stopToken, }; } export function createStopToken() { return URL.createObjectURL?.(new Blob()) || `${Math.random()}`; } function isSharedArrayBuffer(value) { try { return (typeof SharedArrayBuffer !== 'undefined' && value instanceof SharedArrayBuffer); } catch { return false; } } export function stopStopToken(stopToken) { if (stopToken !== undefined) { if (isSharedArrayBuffer(stopToken)) { Atomics.store(new Int32Array(stopToken), 0, 1); } else { URL.revokeObjectURL?.(stopToken); } } } export function checkStopToken(stopToken) { if (stopToken === undefined) { return; } if (isSharedArrayBuffer(stopToken)) { if (Atomics.load(new Int32Array(stopToken), 0) === 1) { throw new Error('aborted'); } } else if (typeof jest === 'undefined' && isWebWorker()) { const xhr = new XMLHttpRequest(); xhr.open('GET', stopToken, false); try { xhr.send(null); } catch { throw new Error('aborted'); } } } export function checkStopToken2(lastCheck) { if (!lastCheck) { return; } const { stopToken, backoff = true, checkInterval = 50, checkIters = 100, } = lastCheck; lastCheck.iters++; if (stopToken === undefined) { return; } if (lastCheck.iters % checkIters !== 0) { return; } if (isSharedArrayBuffer(stopToken)) { checkStopToken(stopToken); } const now = Date.now(); if (now - lastCheck.time > checkInterval) { lastCheck.time = now; checkStopToken(stopToken); if (backoff) { lastCheck.checkInterval ??= checkInterval; lastCheck.checkInterval += checkInterval; } } } export function forEachWithStopTokenCheck(iter, stopToken, arg, durationMs = 400, checkIters = 100, backoff = true) { const lastCheck = { time: Date.now(), iters: 0, checkInterval: durationMs, backoff, checkIters, stopToken, }; let iters = 0; for (const t of iter) { arg(t, iters++); checkStopToken2(lastCheck); } }