Subtlyv0.1.1
Search & loading

loadingIndicator()

Avoid flashes from very short loading states. Avoid spinner flashes.

Available in v0.1.1async.jsPerformance

Try it

Load the report with a fast or slow connection. Both requests show a busy state immediately, but only the longer request displays the spinner after 200 ms.

Live example
Activity report

Choose a request speed.

<div id="your-component">
<div class="demo-row"><button data-ms="100">Fast request · 100 ms</button><button data-ms="900">Slow request · 900 ms</button></div><div class="data-preview report-preview" aria-busy="false"><div class="report-heading"><strong>Activity report</strong><span class="spinner" hidden aria-hidden="true"></span></div><div class="report-bars" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div></div><p class="demo-status" role="status">Choose a request speed.</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 report = el.querySelector('.report-preview');
          const buttons = [...el.querySelectorAll('button')];
          const loader = kit.loadingIndicator(visible => {
            el.querySelector('.spinner').hidden = !visible;
          }, { delay: 200, minVisible: 300 });
          for (const button of buttons) button.addEventListener('click', async () => {
            buttons.forEach(button => { button.disabled = true; });
            report.setAttribute('aria-busy', 'true');
            status('Loading report…');
            loader.start();
            await wait(Number(button.dataset.ms));
            if (signal.aborted) return;
            loader.stop();
            report.setAttribute('aria-busy', 'false');
            buttons.forEach(button => { button.disabled = false; });
            status('Report loaded in ' + button.dataset.ms + ' ms.');
          }, { signal });
          return () => loader.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Add it to your project

  1. 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.
  2. Connect the behavior. Copy the JavaScript tab, update #your-component and initialize it after the elements exist. Replace simulated operations with your own data.
  3. 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

Provide render(show) for a loading region. start() waits before showing the visual indicator; stop() enforces a minimum visible duration to avoid flashes. Defaults: 200 ms delay and 300 ms minimum visibility.

Interface
render, delay, minVisible; start/stop/destroy.
Lifecycle
Use one instance per loading region. destroy() clears timers and hides the visual indicator when the region is removed.

Accessibility and safety

Implementation notes

Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.

aria-busy must track the real request state rather than the spinner's visual delay. Provide meaningful status text when a task needs an explanation.

What to check

Compare fast and slow requests. Check that fast work does not flash a spinner, and that accessibility state clears when the request finishes.

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); }
    };
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close