一、防抖
函数防抖,就是指触发事件后,在 n 秒后只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数的执行时间。
简单的说,当一个动作连续触发,只执行最后一次。
基础版
function debounce(func, wait) {
var timeout;
return function () {
clearTimeout(timeout)
timeout = setTimeout(func, wait);
}
}
function getThisName() {
console.log("name")
}
const obj = {
name : 'name',
}
obj.getName = getThisName;
const fn = debounce(obj.getName, 1000);
fn();
fn();
fn();
fn();
fn();
// name 只执行一次 getName
修改this指向
如果我们在 obj.getName 函数中 console.log(this),在不使用 debounce 函数的时候,this 的值为 obj,但是如果使用我们的 debounce 函数,this 就会指向 Window 对象。
var name = "window";
function debounce(func, wait) {
var timeout;
return function () {
clearTimeout(timeout)
timeout = setTimeout(func, wait);
}
}
function getThisName() {
console.log(this.name)
}
const obj = {
name : 'name',
}
obj.getName = getThisName;
// obj.getName() // 'name'
const fn = debounce(obj.getName, 1000);
fn(); // 'window'
所以我们需要将 this 指向正确的对象。
function debounce(func, wait) {
var timeout;
return function () {
var context = this;
clearTimeout(timeout);
timeout = setTimeout(function() {
func.apply(context)
}, wait);
}
}
const fn = debounce(obj.getName, 1000).bind(obj);
fn();// 'name'
函数参数
在处理函数中会有时还需要处理参数 。
function debounce(func, wait) {
var timeout;
return function () {
var context = this;
var args = arguments;
clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}
const fn = debounce(obj.getName, 1000).bind(obj);
fn("age"); // 'name' 'age'
二、节流
限制一个函数在一定时间内只能执行一次。
关于节流的实现,有两种主流的实现方式,一种是使用时间戳,一种是设置定时器。
使用时间戳
当触发事件的时候,我们取出当前的时间戳,然后减去之前的时间戳(最一开始值设为 0 ),如果大于设置的时间周期,就执行函数,然后更新时间戳为当前的时间戳,如果小于,就不执行。
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 getThisName() {
console.log("name");
}
const obj = {
name : 'name',
}
obj.getName = getThisName;
const fn = throttle(obj.getName, 2000);
fn();
setTimeout(fn, 1000);
setTimeout(fn, 2500);
// name
// name
// 只执行两次
使用定时器
当触发事件的时候,我们设置一个定时器,再触发事件的时候,如果定时器存在,就不执行,直到定时器执行,然后执行函数,清空定时器,这样就可以设置下个定时器。
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)
}
}
}
两个方法比较
- 第一种事件会立刻执行,第二种事件会在 n 秒后第一次执行
- 第一种事件停止触发后没有办法再执行事件,第二种事件停止触发后依然会再执行一次事件
三、常见的应用场景
防抖
连续的事件,只需触发一次的回调场景有:
- 搜索框搜索输入。只需要用户最后一次输入完再发送请求
- 手机号、邮箱格式的输入验证检测
- 窗口大小的 resize 。只需窗口调整完成后,计算窗口的大小,防止重复渲染。
节流
间隔一段时间执行一次回调的场景有:
- 滚动加载,加载更多或滚动到底部监听
- 谷歌搜索框,搜索联想功能
- 高频点击提交,表单重复提交
- 省市信息对应字母快速选择
四、总结
- 函数防抖:将多次操作合并为一次操作进行,原理是维护一个计时器,后设置的定时器会取代之前的定时器,如果高频事件一直在触发那么回调函数一直不会执行。
- 函数节流:使得一定时间内只触发一次函数。原理是通过判断是否满足限制时间,满足则执行。
参考链接:
JavaScript专题之跟着underscore学防抖
JavaScript专题之跟着 underscore 学节流