latestRequest()
Ignore outdated search responses. Race-free search.
Try it
Load Design, then immediately load Engineering. Design is deliberately slower. Only the most recently requested team can appear, even when the earlier request finishes later.
Older results will never replace your latest selection.
Choose a team.
<div id="your-component">
<div class="demo-row"><button data-team="Design" data-ms="1400">Load Design · slow</button><button data-team="Engineering" data-ms="200">Load Engineering · fast</button></div>
<div class="data-preview" aria-busy="false"><span class="muted">Selected team</span><strong data-result>No team loaded</strong><p>Older results will never replace your latest selection.</p></div><p class="demo-status" role="status">Choose a team.</p>
</div>import * as kit from 'subtly';
const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
function setup() {
const panel = el.querySelector('.data-preview');
const request = kit.latestRequest(async (_signal, team, delay) => {
// This mock deliberately ignores cancellation to demonstrate race protection.
await wait(delay);
return team;
});
for (const button of el.querySelectorAll('button')) {
button.addEventListener('click', async () => {
panel.setAttribute('aria-busy', 'true');
status('Loading ' + button.dataset.team + '…');
const result = await request.run(button.dataset.team, Number(button.dataset.ms));
if (signal.aborted || result.status === 'stale') return;
panel.setAttribute('aria-busy', 'false');
if (result.status === 'success') {
el.querySelector('[data-result]').textContent = result.value;
status(result.value + ' loaded. Earlier responses are ignored.');
} else status('Could not load this team. Try again.');
}, { signal });
}
return () => request.destroy();
}
const stop = setup();
// Call when this component is removed.
function cleanup() {
listeners.abort();
stop?.();
}Add it to your project
- Copy the HTML. Use the HTML tab above and place the markup inside a dedicated component root. Layout classes belong to this documentation website; use your own styles.
- Connect the behavior. Copy the JavaScript tab, update
#your-componentand initialize it after the elements exist. Replace simulated operations with your own data. - Clean up on unmount. Call the example’s
cleanup()when the component is removed. It aborts application listeners and releases the utility’s timers or observers.
The preview and JavaScript tab use the same utility wiring. status() writes plain text into the example’s status element. wait() is a simulated local delay. For examples with data-ix attributes, start the declarative runtime once at application level, as shown in the code. Use your framework guide to place setup and cleanup correctly.
API and lifecycle
Wrap task(signal, ...args), then call run(...args) for each new query. Each run aborts the previous signal and uses a generation check so an older result cannot become the newest successful result.
- Interface
task(signal,...args); run, cancel, destroy.- Lifecycle
- run() resolves with success and value, error and error, or stale. Render only a successful current result. cancel() and destroy() invalidate pending work and abort the current signal.
Accessibility and safety
Implementation notes
Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.
Aborting a client request does not reverse a server-side action. Use this for replaceable reads and keep error and loading feedback accessible.
What to check
Start a slow request followed by a fast one, including a task that ignores AbortSignal. Confirm the slow result never replaces the latest result.
View documented module source
/** Wait until calls stop for `delay` ms. Useful for search and autosave.
* Preserves arguments and receiver. Cancel when the component unmounts.
* Do not debounce keyboard feedback or critical submissions. */
export function debounce(fn, delay = 250) {
let timer, args, receiver;
function cancel() { clearTimeout(timer); timer = undefined; args = receiver = undefined; }
function flush() {
if (timer === undefined) return;
const a = args, r = receiver;
cancel();
return fn.apply(r, a);
}
function run(...next) {
cancel(); args = next; receiver = this;
timer = setTimeout(flush, delay);
}
return Object.assign(run, { cancel, flush });
}
/** Latest request wins, even if the request ignores AbortSignal.
* task(signal, ...args) must return data; render only a successful result.
* Example: const search = latestRequest((signal,q) => fetch(url,{signal})); */
export function latestRequest(task) {
let controller, generation = 0;
function cancel() { generation++; controller?.abort(); }
async function run(...args) {
cancel();
const id = generation;
controller = new AbortController();
try {
const value = await task(controller.signal, ...args);
return id === generation ? { status: 'success', value } : { status: 'stale' };
} catch (error) {
return id === generation ? { status: 'error', error } : { status: 'stale' };
}
}
return { run, cancel, destroy: cancel };
}
/** Block concurrent submissions. Server-side idempotency is still required
* for payments, orders, and other irreversible writes. */
export function singleFlight(task) {
let busy = false;
return { get busy() { return busy; }, async run(...args) {
if (busy) return { status: 'busy' };
busy = true;
try { return { status: 'success', value: await task(...args) }; }
finally { busy = false; }
}};
}
/** Avoid spinner flashes for short requests, but keep a displayed spinner
* visible for at least minVisible ms. Use one instance per loading region.
* aria-busy should reflect actual request state, not this visual delay. */
export function loadingIndicator(render, { delay = 200, minVisible = 300 } = {}) {
let timer, visible = false, started = 0, destroyed = false;
function set(value) { if (visible === value) return; visible = value; if (value) started = Date.now(); render(value); }
return {
start() { if (destroyed) return; clearTimeout(timer); if (!visible) timer = setTimeout(() => set(true), delay); },
stop() { if (destroyed) return; clearTimeout(timer); if (visible) timer = setTimeout(() => set(false), Math.max(0, minVisible - (Date.now() - started))); },
destroy() { destroyed = true; clearTimeout(timer); set(false); }
};
}