Skip to content

Instantly share code, notes, and snippets.

@zerosignalproductions
Last active January 6, 2017 19:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerosignalproductions/7323202 to your computer and use it in GitHub Desktop.
Save zerosignalproductions/7323202 to your computer and use it in GitHub Desktop.
JS Throttled Resize event using requestAnimationFrame
/**
* Throttled Resize event
* Updated to use requestAnimationFrame instead of setTimeout
* Original: https://github.com/louisremi/jquery-smartresize
*/
var $specialThrottle,
dummy = {_:0},
frame = 0,
wasResized,
animRunning;
$specialThrottle = $.event['special']['throttledresize'] = {
'threshold': 3,
'setup': function() {
$(this).on( 'resize', $specialThrottle['handler'] );
},
'teardown': function() {
$(this).off( 'resize', $specialThrottle['handler'] );
},
'handler': function( event, execAsap ) {
// Save the context
var context = this,
args = arguments;
wasResized = true;
if (!animRunning ) {
animRunning = true;
$specialThrottle.animate(context, args, event, execAsap);
}
},
'animate': function(context, args, event, execAsap) {
frame++;
if ( frame > $specialThrottle['threshold'] && wasResized || execAsap ) {
event.type = 'throttledresize';
$.event['dispatch'].apply( context, args );
wasResized = false;
frame = 0;
}
if ( frame > 9 ) {
window.cancelAnimationFrame($specialThrottle.animate);
$(dummy).stop();
animRunning = false;
frame = 0;
}
if(animRunning) {
window.requestAnimationFrame(function() {
$specialThrottle.animate(context, args, event, execAsap);
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment