Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Last active July 31, 2019 11:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cferdinandi/9029584 to your computer and use it in GitHub Desktop.
Save cferdinandi/9029584 to your computer and use it in GitHub Desktop.
A technique for throttling listener events (like resize or scroll) for better performance. https://developer.mozilla.org/en-US/docs/Web/Reference/Events/resize
var eventTimeout; // Set timeout variable
/**
* The function that runs the event actions
*/
var actualEventHandler = function () {
// handle the event...
};
/**
* Throttle events to only run at 15fps
*/
var eventThrottler = function () {
// ignore resize events as long as an actualResizeHandler execution is in the queue
if ( !eventTimeout ) {
eventTimeout = setTimeout(function() {
eventTimeout = null;
actualEventHandler();
}, 66);
}
};
// Run the event listener
window.addEventListener( 'resize', eventThrottler, false );
@vivmaha
Copy link

vivmaha commented Aug 11, 2016

I've wrapped similar logic into a reusable module here

@IAMtheIAM
Copy link

IAMtheIAM commented Apr 15, 2019

Resize events are not getting ignored when I used this. It ques up all the actualEventHandler() and then they all happen at once

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment