A helper function to delay the execution of certain code.
npm i @cloudwell/debounce
This example will notify the consumer of the SearchTextBox
component after each keystroke.
export interface ISearchTextBoxProps {
onSearchTextChanged: (e) => void;
}
const SearchTextBox: React.FC<ISearchTextBoxProps> = (props) => {
const onSearchTextBoxChanged = (e) => {
console.log("Search Text Changed!");
props.onSearchTextChanged(e);
}
return <input onChange={onSearchTextBoxChanged} />;
}
export default SearchTextBox;
This example will only notify the consumer of the SearchTextBox
component after the user has stopped typing for 500 milliseconds.
import { debounce } from '@cloudwell/debounce';
export interface ISearchTextBoxProps {
onSearchTextChanged: (e) => void;
}
const SearchTextBox: React.FC<ISearchTextBoxProps> = (props) => {
const onSearchTextBoxChanged = debounce((e) => {
console.log("Search Text Changed!");
props.onSearchTextChanged(e);
}, 500)
return <input onChange={onSearchTextBoxChanged} />;
}
export default SearchTextBox;
This example will only notify the consumer of the SearchTextBox
component after the user has stopped typing for 500 milliseconds but will allow the SearchTextBox
to utilize the immediate event for updating the UI with each keystroke.
import { debounce } from '@cloudwell/debounce';
export interface ISearchTextBoxProps {
onSearchTextChanged: (e) => void;
}
const SearchTextBox: React.FC<ISearchTextBoxProps> = (props) => {
const [searchText, setSearchText] = useState('');
const onSearchTextBoxChanged = debounce(
(e) => {
console.log("Search Text Changed!");
props.onSearchTextChanged(e);
},
500,
(e) => {
setSearchText(e.target.value);
})
return <input onChange={onSearchTextBoxChanged} value={searchText} />;
}
export default SearchTextBox;
Parameter | Type | Default value | Description |
---|---|---|---|
callback | Function | undefined | Required. The code to debounce. |
delay | Number | undefined | Required. The number of milliseconds to delay execution. |
immediate | Function | undefined | Optional. Code that is not debounced. |