Skip to content

Instantly share code, notes, and snippets.

@mjlescano
Last active January 15, 2016 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjlescano/c4a70f4cd4460cd39c11 to your computer and use it in GitHub Desktop.
Save mjlescano/c4a70f4cd4460cd39c11 to your computer and use it in GitHub Desktop.
window.onresize handler with a debounced calling to avoid unnecessary re-paints
/**
* onResize.js
*
* `window.onresize` handler with a debounced calling to avoid unnecessary re-paints.
*
* e.g.:
* onResize.add(function(){
* console.log('Executed on window resize! But debounced.')
* })
*
* Matías Lescano | @mjlescano
* Licensed under the MIT license
*/
;if( !window.onResize ) (function(w){
function debounce (func, wait, immediate) {
var timeout
return function () {
var context = this
var 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)
}
}
var cbs = []
var execute = debounce(function _execute() {
for (var i = 0, l = cbs.length; i < l; i++) cbs[i]()
}, 300)
if (w.addEventListener) {
w.addEventListener('resize', execute)
} else {
w.attachEvent('onresize', execute)
}
w.onResize = {
add: function(cb){
cbs.push(cb)
return w.onResize
},
remove: function(cb){
for (var i = 0, l = cbs.length; i < l; i++) {
if (cb === cbs[i]) {
cbs.splice(i,1)
break
}
}
return w.onResize
}
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment