Last active
January 6, 2017 19:33
-
-
Save zerosignalproductions/7323202 to your computer and use it in GitHub Desktop.
JS Throttled Resize event using requestAnimationFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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