Skip to content

Instantly share code, notes, and snippets.

@Avinava
Last active July 7, 2022 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Avinava/59459e3b35f932266147fb642bd5a894 to your computer and use it in GitHub Desktop.
Save Avinava/59459e3b35f932266147fb642bd5a894 to your computer and use it in GitHub Desktop.
Debouncing in LWC
/* eslint-disable @lwc/lwc/no-async-operation */
export default class Debounce extends LightningElement {
doApiCallDebounced;
connectedCallback() {
// generate the debounce handler
this.doApiCallDebounced = this.debounce(this.doApiCall, 1000);
}
// called directly from onchange of the input
handleSearchInputChange(event) {
// avoid sending the event
// since they can become null in async calls
this.doApiCallDebounced(event.detail.value);
}
doApiCall(searchStr) {
// makes the actual api call
// and needs to be debounced
}
debounce(callback, time) {
let interval;
const self = this;
return function (...args) {
clearTimeout(interval);
interval = setTimeout(function () {
interval = null;
callback.bind(self)(...args);
}, time);
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment