A while back i asked for a javascript function that would allow me to resize content within a browser window at a set interval. Like, not with every pixel-sized change. I was given this function:
function throttle (func, wait) {
var throttling = false;
return function(){
if ( !throttling ){
func.apply(this, arguments);
throttling = true;
setTimeout(function(){
throttling = false;
}, wait);
}
};
}
window.onresize = throttle(function() {
resize_columns();
}, 20);
The person said that at that time s/he did not really have time to explain closures. I still don’t understand how it works. Can someone explain it to me?
Thank you.
The anonymous function being returned forms a closure over the ‘throttling’ variable. So even when your stack unrolls, and the function throttle() goes ‘out of scope’. The anonymous function will STILL have access to the ‘throttling’ variable.
Closures are awesome.. I use them ever day and they are still like magic for me.. (It’s less magical once you understand how they are implemented on the heap but I digress 🙂