26 03/2015

window resize trigger once

最后更新: Thu Mar 26 2015 10:38:35 GMT+0800

function debouncer( func , timeout ) {
var timeoutID , timeout = timeout || 200;
return function () {
var scope = this , args = arguments;
clearTimeout( timeoutID );
timeoutID = setTimeout( function () {
func.apply( scope , Array.prototype.slice.call( args ) );
} , timeout );
}
}

$( window ).resize( debouncer( function ( e ) {
// do stuff
} ) );

$(window).resize(function() {
clearTimeout($.data(this, ‘resizeTimer’));
$.data(this, ‘resizeTimer’, setTimeout(function() {
//do something
alert(“Haven’t resized in 200ms!”);
}, 200));
});

(function ($) {
var methods = { on: $.fn.on, bind: $.fn.bind };
$.each(methods, function(k){
$.fn[k] = function () {
var args = [].slice.call(arguments),
delay = args.pop(),
fn = args.pop(),
timer;

        args.push(function () {
            var self = this,
                arg = arguments;
            clearTimeout(timer);
            timer = setTimeout(function(){
                fn.apply(self, [].slice.call(arg));
            }, delay);
        });

        return methods[k].apply(this, isNaN(delay) ? arguments : args);
    };
});

}(jQuery));
Use it like any other on or bind-event handler, except that you can pass an extra parameter as a last:

$(window).on(‘resize’, function(e) {
console.log(e.type + ‘-event was 200ms not triggered’);
}, 200);