Debounce resize
Resize debouncer that can be reconfigured after it is installed.
by doug65536
HTML
<button id="short_delay">Short delay</button>
<button id="long_delay">Long delay</button>
<button id="get_delay">Get delay</button>
<button id="bind">Bind</button>
<button id="unbind">Unbind</button>
<div id="log"></div>
JavaScript
(function($) {
debugger;
var debounce_resize = function(delay, handler) {
var context = this;
var bound = false;
var cur_timeout = null;
var usr_width = null, usr_height = null;
var cur_width = null, cur_height = null;
if (typeof delay == 'function' && typeof handler == 'undefined') {
handler = delay;
delay = 250;
}
var cancel_timeout = function() {
if (cur_timeout !== null) {
clearTimeout(cur_timeout);
cur_timeout = null;
}
};
var call_handler = function() {
if (usr_width !== cur_width || usr_height !== cur_height) {
handler.call(context, cur_width, cur_height);
usr_width = cur_width;
usr_height = cur_height;
}
};
var resize_handler = function() {
var new_width = context.width(), new_height = context.height();
cur_width = new_width;
cur_height = new_height;
cancel_timeout();
if (usr_width !== new_width || usr_height !== new_height) {
cur_timeout = setTimeout(call_handler, delay);
}
};
var command_handler;
command_handler = function(command, arg) {
switch (command) {
case 'unbind':
if (bound) {
context.unbind('resize', resize_handler);
cancel_timeout();
bound = false;
}
return command_handler;
case 'bind':
if (!bound) {
context.on('resize', resize_handler);
bound = true;
}
return command_handler;
...