javascript函数的throttle和debounce
throttle
鼠标移动,mousemove 事件
DOM 元素动态定位,window对象的resize和scroll 事件
debounce
文本输入keydown 事件,keyup 事件,例如做autocomplete
/*
* 频率控制 返回函数连续调用时,fn 执行频率限定为每多少时间执行一次
* @param fn {function} 需要调用的函数
* @param delay {number} 延迟时间,单位毫秒
* @param immediate {bool} 给 immediate参数传递false 绑定的函数先执行,而不是delay后后执行。
* @return {function}实际调用函数
*/
var throttle = function (fn,delay, immediate, debounce) {
var curr = +new Date(),//当前事件
last_call = 0,
last_exec = 0,
timer = null,
diff, //时间差
context,//上下文
args,
exec = function () {
last_exec = curr;
fn.apply(context, args);
};
return function () {
curr= +new Date();
context = this,
args = arguments,
diff = curr - (debounce ? last_call : last_exec) - delay;
clearTimeout(timer);
if (debounce) {
if (immediate) {
timer = setTimeout(exec, delay);
} else if (diff >= 0) {
exec();
}
} else {
if (diff >= 0) {
exec();
} else if (immediate) {
timer = setTimeout(exec, -diff);
}
}
last_call = curr;
}
};
/*
* 空闲控制 返回函数连续调用时,空闲时间必须大于或等于 delay,fn 才会执行
* @param fn {function} 要调用的函数
* @param delay {number} 空闲时间
* @param immediate {bool} 给 immediate参数传递false 绑定的函数先执行,而不是delay后后执行。
* @return {function}实际调用函数
*/
var debounce = function (fn, delay, immediate) {
return throttle(fn, delay, immediate, true);
};
扫一扫订阅我的微信号:IT技术博客大学习
- 作者:愚人码头 来源: WEB前端开发
- 标签: debounce throttle
- 发布时间:2013-07-08 22:43:51
-
[83] memory prefetch浅析
-
[53] 转载:cassandra读写性能原理分析
-
[51] 基本排序算法的PHP实现
-
[50] 深入浅出cassandra 4 数据一致性问
-
[46] 字符引用和空白字符
-
[42] MySQL半同步存在的问题
-
[40] 获取Dom元素的X/Y坐标
-
[39] Inline Form Labels
-
[39] javascript插入样式
-
[38] JS中如何判断字符串类型的数字