Subtlyv0.1.1
Search & loading

debounce()

Search after typing pauses. Search, draft updates.

Available in v0.1.1async.jsPerformance

Try it

Search this local reading list. Type “design” and watch the list update after you stop typing for 300 ms. The counter shows how much filtering actually ran.

Live example
  • Designing a useful empty state
  • Accessible menus from the start
  • Small details in product design
  • A guide to loading feedback

4 articles · 0 filter runs

<div id="your-component">
<label>Find an article<input type="search" placeholder="Try design or accessibility" autocomplete="off"></label>
        <ul class="result-list"><li>Designing a useful empty state</li><li>Accessible menus from the start</li><li>Small details in product design</li><li>A guide to loading feedback</li></ul>
        <p class="demo-status" role="status">4 articles · 0 filter runs</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 input = el.querySelector('input');
          const articles = [...el.querySelectorAll('li')];
          let runs = 0;
          const filter = kit.debounce(query => {
            runs++;
            for (const article of articles) {
              article.hidden = !article.textContent.toLowerCase().includes(query.toLowerCase());
            }
            const count = articles.filter(article => !article.hidden).length;
            status(`${count} articles · ${runs} filter runs`);
          }, 300);
          input.addEventListener('input', () => filter(input.value), { signal });
          return () => filter.cancel();
}
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

Wrap an expensive callback, then call the returned function with the latest input. Repeated calls restart the timer; the callback receives the most recent arguments and receiver. The default delay is 250 ms.

Interface
fn, delay; cancel, flush.
Lifecycle
cancel() drops queued work. flush() runs queued work immediately. Cancel pending work when the component unmounts to avoid updating a removed view.

Accessibility and safety

Implementation notes

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

Use this for search or draft updates. Keep typing, focus, validation recovery and critical submit feedback immediate.

What to check

Type several characters quickly and confirm one callback runs after the pause. Unmount before the delay ends and confirm the callback does not 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); }
    };
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close