Last active
July 7, 2022 10:04
-
-
Save Avinava/59459e3b35f932266147fb642bd5a894 to your computer and use it in GitHub Desktop.
Debouncing in LWC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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