Debounce Window resize callbacks in JavaScript

It's important to debounce the calls you do when listening to the resize window event. Otherwise your function could be called hundreds of times, slowing the user's performance.

The debounce function

We need the black magic first.

function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) { func.apply(context, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; }

Your code here

As you can see we're passing a callback function and a timeout. You can experiment with different values to make it look more real time.

var myEfficientCode = debounce(function() { // Your code here }, 250);



Leave a Reply

Add <code> Some Code </code> by using this tags.