场景
- window对象频繁的onresize,onscroll等事件
- 拖拽的mousemove事件
- 文字输入,keyup事件
- …
- …
防抖 (debounce)
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
例如搜索框, 每输入一个字符, 都向后端发一次请求,调节为最后一次输入后一定时间再触发, 只触发最后一次 (防抖)
function debounce(func, wait) {
var timeout;
return function () {
var context = this;
var args = arguments;
clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}
节流(throttle)
降低代码执行的频率,保证一段时间内核心代码只执行一次
例如之前写的滚动布局,不使用节流会疯狂触发scroll
//时间戳版
// 第一版
function throttle(func, wait) {
var context, args;
var previous = 0;
return function() {
var now = +new Date();
context = this;
args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}
//定时器版本
// 第二版
function throttle(func, wait) {
var timeout;
var previous = 0;
return function() {
context = this;
args = arguments;
if (!timeout) {
timeout = setTimeout(function(){
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
时间戳版和定时器版的节流函数的区别就是:
时间戳版的函数触发是在时间段内开始的时候,而定时器版的函数触发是在时间段内结束的时候。