项目上线后, 经常会报出用户一直点击导致连续出发事件引发体验上的问题, 尤其是在监听浏览器滚动 scroll, 页面调整 resise 的时候, 这个时候我们就需要通过节流 / 防抖来优化这个问题;
防抖:
防抖就是指在某个时间内再次触发事件则会进行重新计时, 也就是说一直触发事件则时间在不断重置; 举个例子:
- function debounce(method, delay){
- var timer = null;
- return function(){
- var context = this,args = arguments;
- clearTimeout(timer);
- timer = setTimeout(function(){
- method.apply(context, args);
- },delay);
- }
- }
节流:
所谓节流, 就是指在高频触发事件时, 只有在大于设定的周期时间内才去触发一次, 触发后这个周期时间清零重新开始计算, 和防抖的区别就是为了确保在这个周期时间只执行一次;
- function throttle(method, delay){
- var last = 0;
- return function (){
- var now = +new Date();
- if(now - last> delay){
- method.apply(this,arguments);
- last = now
- }
- }
- }
来源: http://www.jianshu.com/p/1051bfbf8714