@icaruk/debounce
v1.1.0
Published
Javascript simple debouncer (and throttle)
Downloads
3
Maintainers
Readme
debounce is a javascript debouncer (and throttle) that instead returning a debounced function it will execute it after the specified time.
- 😃 Easy to use.
- 🚀 Lightweight (1.6 KB)
- ⚪️ Zero dependencies.
⬇️ Import
const debounce = require("@icaruk/debounce");
🧭 Usage:
debounce(wait, fnc, id, reverse);
- wait (number) Number of miliseconds that must pass before the function executes.
- fnc (function) Function that will be executed.
- id (string)
Unique identifier of the performed action. If the
id
is ommited thefnc
argument will be stringified and used asid
(less optimal). - reverse (boolean)
Default
false
. Iftrue
it will throttle instead debounce.
🔮 Examples:
Debounce without id
const hello = (name) => {
console.log( "Hello!" );
};
debounce(1000, hello);
debounce(1000, hello);
debounce(1000, hello);
// > Outputs:
// Hello!
Debounce with id
const hello = () => {
console.log( "Hello!" );
};
debounce(1000, hello, "button");
debounce(1000, hello, "button");
debounce(1000, hello, "button_2");
// > Outputs:
// Hello!
// Hello!
Throttle with id
const hello = (name) => {
console.log( `Hello ${name}!` );
};
debounce(1000, () => hello(0), "button", true);
debounce(1000, () => hello(1), "button", true);
debounce(1000, () => hello(2), "button", true);
// > Outputs:
// Hello 0!
🔮 Passing arguments:
✅ GOOD
const hello = (name = "") => {
console.log( `Hello ${name}!` );
};
debounce(1000, () => hello("Mike"));
debounce(1000, () => hello("Bob"));
debounce(1000, () => hello("Susan"));
// > Outputs:
// Hello Mike!
// Hello Bob!
// Hello Susan!
❌ BAD
const hello = (name = "") => {
name = " " + name;
console.log( `Hello ${name}!` );
};
debounce(1000, hello("Mike")); // ❌
debounce(1000, hello("Bob")); // ❌
debounce(1000, hello("Susan")); // ❌
// > Outputs:
// Hello!
// [Error] debounce: fnc is null
// Hello!
// Hello!
// [Error] debounce: fnc is null
// [Error] debounce: fnc is null