debounce-microtask
Debounce a function using a microtask.
- Zero dependencies
- Zero configuration
- Passes through the most recent invocation parameters
- 100% test coverage
- TypeScript definitions
Installation
npm install --save debounce-microtask
# or
yarn add debounce-microtask
Usage
Define a function, then use debounceMicrotask
to create debounced version.
import { debounceMicrotask } from "debounce-microtask";
function example(text) {
console.log(text);
}
const debouncedExample = debounceMicrotask(example);
debouncedExample("Hello world!");
debouncedExample("Goodbye world!");
// logs "Goodbye world!"
Often it's simpler to do it inline:
import { debounceMicrotask } from "debounce-microtask";
const example = debounceMicrotask(text => {
console.log(text);
});
example("Hello world!");
example("Goodbye world!");
// logs "Goodbye world!"
Background
When working with JavaScript in a browser, it can be useful to debounce a function (as a performance optimisation), but still guarantee that it is executed before the browser's next paint.
For example typestyle-react builds React components that lazily computes and flushes stylesheets to the DOM and guarantees prevention of flash-of-unstyled-content (FOUC).
Building on this, libraries that perform DOM measurement (e.g. to absolute position a tooltip) need to wait until styles are flushed to the DOM.