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
- [272] 招聘技巧一二
- [14] linux内核研究笔记(一)内存管理 – p
- [13] 个人开公司的流程,以后用得着
- [13] 我对技术方向的一些反思
- [12] Nginx+FastCgi+Php 的工作机
- [11] Linux常用系统信息查看命令
- [11] 在FreeNAS/BSD搭建基于Nginx+
- [11] Redis和Memcached的区别
- [10] 关于大学学习,说说我的一些体会
- [10] 我的程序员之路