Debouncing and Throttling are pretty commonplace in the JS world, but rarely do I see developers use it when building Drupal theme behaviors or JS in modules, but did you know Debounce is part of DRUPAL CORE?!
Yes, my friends, you heard it correct, this shit is built in.
Preamble: Debouce vs. Throttle.
Scenario: A user is typing into a field that I want to save the input, on key up I fire my event.
Debounce: Wait until at least X amount of time has passed between calls before I hit my server with AJAX requests
Throttle: Only send to my server once per X time during events.
Both obviously have their pro's and cons and use-cases, but I'll leave that for another discussion.
Drupal Debounce
One of the most common uses I see is when a user is resizing the browser, commonly to re-adjust a fixed element or non-css controlled calculation. The problem here is you don't care about WHILE the user is resizing, you care about what size they end up at.
So instead of spamming our poor code with window sizes that don't matter, lets debounce this shit:
First, you'll want to add the core debounce as a dependency to your JS library:
javascriptdependencies: - core/jquery - core/drupal - core/drupal.debounce
Next, lets use the example of calculation of a resize event:
javascript
// Recalculate Component on window resize.
var resizeComponent = function () {
var component = document.getElementById('cool-component');
component.style.width = (window.innerWidth * 0.8675309) + 'px';
};
// Resize my cool component based on window size.
window.addEventListener('resize', Drupal.debounce(resizeComponent, 250, false));
So my resize is triggered after 250ms of not resizing. You'll notice the extra variable "false" at the end, this is an optional parameter that I included to show that the debounce function accepts a bool for immediate firing at the beginning as well as after the timeout.
Cool stuff I tells ya.