45 lines
1.0 KiB
JavaScript
45 lines
1.0 KiB
JavaScript
/** Wall-clock + idle abort for QVAC completion streams. No Bare imports. */
|
|
|
|
function attachCompleteWatch(opts) {
|
|
opts = opts || {};
|
|
const timeoutMs = Number(opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : 0;
|
|
const idleMs = Number(opts.idleMs) > 0 ? Number(opts.idleMs) : 0;
|
|
const abort = opts.abort;
|
|
let timedOut = false;
|
|
let wall = null;
|
|
let idle = null;
|
|
|
|
function clear() {
|
|
if (wall) clearTimeout(wall);
|
|
if (idle) clearTimeout(idle);
|
|
wall = null;
|
|
idle = null;
|
|
}
|
|
|
|
function fire() {
|
|
if (timedOut) return;
|
|
timedOut = true;
|
|
clear();
|
|
try {
|
|
if (typeof abort === 'function') abort();
|
|
} catch (_) {}
|
|
if (typeof opts.onTimeout === 'function') opts.onTimeout();
|
|
}
|
|
|
|
if (timeoutMs) wall = setTimeout(fire, timeoutMs);
|
|
|
|
function bump() {
|
|
if (timedOut || !(idleMs > 0)) return;
|
|
if (idle) clearTimeout(idle);
|
|
idle = setTimeout(fire, idleMs);
|
|
}
|
|
|
|
return {
|
|
bump,
|
|
clear,
|
|
timedOut: () => timedOut,
|
|
};
|
|
}
|
|
|
|
module.exports = { attachCompleteWatch };
|