Adding a debounce to Drupal JS behaviors

Here's how I debounce JS with an example in a Drupal JS behavior. For more information on Drupal behaviors, see the links at the bottom of the page.
(function ($) {
  'use strict';
  Drupal.behaviors.exampleResizeBehavior = {
    attach: function (context) {
      // Resize timeout event ID.
      var resizeTimeoutId;
      // Resize timeout duration in milliseconds.
      var resizeTimeoutDuration = 100;
 
      /**
       * Debounces resizing behaviors.
       */
      var resizeDebounce = function() {
        clearTimeout(resizeTimeoutId);
        resizeTimeoutId = setTimeout(doneResizing, resizeTimeoutDuration);
      };
 
      /**
       * Main screen resize logic.
       *
       * This function is called after the screen is finished resizing.
       */
      var doneResizing = function() {
        alert(Drupal.t('Fugazi is a rad band!'));
      };
 
      /**
       * Window resize events.
       */
      $(window).resize(resizeDebounce);
 
    }
  };
})(jQuery);

Tags

Internal References

External References

Article Type

General