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


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);
};


About the Author

Jacob Lett (Jake) is the founder of Bootstrap Creative, a B2B marketing consultancy specializing in manufacturers and industrial companies. A HubSpot-certified CMS developer, SEO, Answer Engine Optimization (AEO), and RevOps professional, he helps B2B companies improve their websites, search visibility, HubSpot systems, and Google Ads campaigns to generate more qualified leads and RFQs. With over a decade of hands-on experience, he acts as a direct partner for companies seeking measurable ROI from their marketing investment.



Related posts
Category: Code Snippets

Tags: ,

| Read My Editorial Policy

Want to Get Email Updates of New Articles?

Join My Email Newsletter