您可以使用setTimeout(),并clearTimeout()连同jQuery.data:
$(window).resize(function() {
clearTimeout($.data(this, 'resizeTimer'));
$.data(this, 'resizeTimer', setTimeout(function() {
//do something
alert("Haven't resized in 200ms!");
}, 200));
});
更新资料
我写了一个扩展来增强jQuery的默认on(&bind)-event-handler。如果在给定时间间隔内未触发事件,则它将针对一个或多个事件的事件处理程序函数附加到所选元素。如果您只想在延迟(例如resize事件)之后才触发回调,则这很有用。
https://github.com/yckart/jquery.unevent.js
;(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));
像其他任何处理程序on或bind-event处理程序一样使用它,除了可以在最后传递一个额外的参数外:
$(window).on('resize', function(e) {
console.log(e.type + '-event was 200ms not triggered');
}, 200);
http://jsfiddle.net/ARTsinn/EqqHx/