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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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.
1 2 3 4 5 |
var myEfficientCode = debounce(function() { // Your code here }, 250); |
Enjoy.
Anthony Tornambe
Thanks for sharing a great post!
Rick
You’re welcome!