Debounce a function using a microtask
npm install debounce-microtaskDebounce a function using a microtask.
* Zero dependencies
* Zero configuration
* Passes through the most recent invocation parameters
* 100% test coverage
* TypeScript definitions
``sh`
npm install --save debounce-microtaskor
yarn add debounce-microtask
Define a function, then use debounceMicrotask to create debounced version.
`ts
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:
`ts
import { debounceMicrotask } from "debounce-microtask";
const example = debounceMicrotask(text => {
console.log(text);
});
example("Hello world!");
example("Goodbye world!");
// logs "Goodbye world!"
``
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.