Throttle or Delay JavaScript Functions When Window is Resized [code snippet]

Browse My Free Website Guides

Underscore.js has a popular method for throttling and debouncing functions to prevent them from firing multiple times when a window is resized. I found this delay function that works for times when you don’t need to load the entire underscore library to achieve a similar effect.

// delay function to use on resize to prevent multiple resize events
var delay = (function () {
  var timer = 0;
  return function (callback, ms) {
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();

// Add the delayed functions here
const delayedFunctions = function () {
    console.log('delayedFunctions running');
}

// document ready
$( document ).ready(function() {
    // delayedFunctions on load
    delayedFunctions();
});

// window resize
window.onresize = function(event) {
  delay(function(){
    console.log('Window Resize...');
    delayedFunctions();
  }, 500);
};


Related resources

  • HubSpot CMS vs WordPress: Feature Comparison and Review
  • 25+ Questions to Ask Before Redesigning Your Business Website
  • 5 Things A Business Should Consider Before a Website Redesign
  • How to Get a Responsive Website for Your Manufacturing Company
  • What Is a Good WordPress Alternative for Businesses?
  • Tags: ,

    Want to Get Email Updates of New Posts? Join My Email Newsletter