防止多次触发某个函数
如浏览器窗口大小改变会重复触发onresize事件。 调用方法 window.onresize = debounce(SetViewerSize, 100, false);
/*
* @parm func 调用的函数名
* @parm threshold 防抖动时间间隔
* @parm execAsap 尽快执行 execute as soon as possible
*/
function debounce(func, threshold, execAsap) {
var timeout;
return function debounced() {
var obj = this, args = arguments;
function delayed() {
if (!execAsap)
func.apply(obj, args);
timeout = null;
}
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}