throttleapp
咱们这里说的throttle就是函数节流的意思。再说的通俗一点就是函数调用的频度控制器,是连续执行时间间隔控制。主要应用的场景好比:函数
1.鼠标移动,mousemove 事件
2.DOM 元素动态定位,window对象的resize和scroll 事件this
有人形象的把上面说的事件形象的比喻成机关枪的扫射,throttle就是机关枪的扳机,你不放扳机,它就一直扫射。咱们开发时用的上面这些事件也是同样,你不松开鼠标,它的事件就一直触发。例如:插件
复制代码 代码以下:对象
var resizeTimer=null;
$(window).on('resize',function(){
if(resizeTimer){
clearTimeout(resizeTimer)
}
resizeTimer=setTimeout(function(){
console.log("window resize");
},400);事件
debounce开发
debounce和throttle很像,debounce是空闲时间必须大于或等于 必定值的时候,才会执行调用方法。debounce是空闲时间的间隔控制。好比咱们作autocomplete,这时须要咱们很好的控制输入文字时调用方法时间间隔。通常时第一个输入的字符立刻开始调用,根据必定的时间间隔重复调用执行的方法。对于变态的输入,好比按住某一个建不放的时候特别有用。io
debounce主要应用的场景好比:
文本输入keydown 事件,keyup 事件,例如作autocompleteconsole
这类网上的方法有不少,好比Underscore.js就对throttle和debounce进行封装。jQuery也有一个throttle和debounce的插件:jQuery throttle / debounce,全部的原理时同样的,实现的也是一样的功能。再奉上一个本身一直再用的throttle和debounce控制函数:ast
复制代码 代码以下:
/** 频率控制 返回函数连续调用时,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);