singleFlight()
Prevent repeat submissions while saving. Prevent duplicate in-flight submissions.
Try it
Click Save preferences several times during the one-second request. The button stays available so you can test repeated input, but the request counter increases only once.
Repeated clicks share one pending save.
Ready to save.
<div id="your-component">
<div class="data-preview"><span class="muted">Newsletter preferences</span><strong>Product updates, once a month</strong><p>Repeated clicks share one pending save.</p></div><button>Save preferences</button><div class="demo-metrics"><span>Requests started <strong data-count>0</strong></span><span>Save state <strong data-state>Idle</strong></span></div><p class="demo-status" role="status">Ready to save.</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() {
let calls = 0;
const state = el.querySelector('[data-state]');
const save = kit.singleFlight(async () => {
el.querySelector('[data-count]').textContent = String(++calls);
state.textContent = 'Saving';
await wait(1000); // Replace with your authenticated request.
});
el.querySelector('button').addEventListener('click', async () => {
try {
const result = await save.run();
if (signal.aborted) return;
if (result.status === 'busy') { status('The existing save is still running.'); return; }
state.textContent = 'Saved';
status('Preferences saved. Only one request ran at a time.');
} catch {
state.textContent = 'Failed';
status('Save failed. Please try again.');
}
}, { signal });
}
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 an async task and call run(...args). While a call is pending, further activations return status busy instead of starting another operation. busy exposes the current in-flight state.
- Interface
task; run, busy; rejects on failure.- Lifecycle
- A successful result contains status success and value. Task failures reject, so handle them with try/catch. busy resets in finally after either outcome.
Accessibility and safety
Implementation notes
Client protection is not server-side idempotency.
This prevents concurrent client calls only. Critical writes still need server-side idempotency. Keep disabled or busy controls understandable to keyboard and screen-reader users.
What to check
Activate repeatedly while saving and confirm one task starts. Reject the task and verify an error appears and a later retry can run.
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); }
};
}