0.2.2 • Published 4 years ago
dbouncer v0.2.2
dbouncer
Generate mutable debounce functions.
Usage
In a typical debounce, you set the function when you are creating it, so it will always be calling the same function. Dbouncer let's you change the function before it is called.
import dbouncer from 'dbouncer';
const debounceFn = dbouncer(); // creating a mutable debounce function
inputElement.addEventListener('input', (e) => {
if(e.target.value.length > 10)
debounceFn(() => console.log('more than 10 chars'), 700);
else
debounceFn(() => console.log('up to 10 chars'), 700);
// Every time input event fires, you can set a different function
// to debounceFn. After 700 ms with no new input,
// debounceFn will run the last setted function.
})
Presetting the wait time:
You can also preset the wait time right in the dbouncer function
const debounceFn = dbouncer(700); // presetting fire wait to 700 ms
inputElement.addEventListener('input', (e) => {
if(e.target.value.length > 10)
debounceFn(() => console.log('more than 10 chars'));
else
debounceFn(() => console.log('up to 10 chars'));
// After 700 ms with no new input, debounceFn will run the
// last setted function.
})
Clearing debounce function:
The generated debounce function has a clear() method attached to it.
import dbouncer from 'dbouncer';
const debounceFn = dbouncer();
inputElement.addEventListener('input', (e) => {
debounceFn(() => console.log(e.target.value), 700);
if(!e.target.value){
debounceFn.clear();
// clearing debounceFn function if "e.target.value"
// is falsy, so console.log() will not be called.
}
})
Using dbouncer as a typical debounce function:
You can also use dbouncer as a any typical debounce function.
import dbouncer from 'dbouncer';
var counter = 0;
inputElement.addEventListener('input', dbouncer(() => {
console.log(++counter);
}, 500));
// after 500 ms with no new input, dbouncer function will be called
/**
* PLUS: the function you set in dbouncer will receive the same
* parameters that would be originaly passed to dbouncer().
*/
inputElement.addEventListener('input', dbouncer(e => {
console.log(e.target.value);
// using "e" object that was passed to dbouncer()
}, 500));
Installation
- Install it using npm or yarn
npm install --save dbouncer
yarn add dbouncer
- Import it
import dbouncer from 'dbouncer'
- Use it 😄