1.1.0 ā€¢ Published 3 years ago

@icaruk/debounce v1.1.0

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

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 the fnc argument will be stringified and used as id (less optimal).
  • reverse (boolean) Default false. If true 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