函数节流和函数防抖是一种优化方法,可用于减小高频繁触发任务(函数)的执行次数,达到减小资源占用的目的。jquery
咱们以滚动条的监听事件为例,首先看看使用函数节流和函数防抖前的现象。bash
let count = 0;
$(document).scroll(function () {
console.log(`触发了${++count}次!`);
});
复制代码
实现闭包
let count = 0;
$(document).scroll(throttle(function () {
console.log(`触发了${++count}次!`);
}, 500));
function throttle(fn, wait) {
let canRun = true;
return function () {
if (!canRun) {
return;
}
canRun = false;
setTimeout(() => {
fn.apply(this, arguments); //让scroll的回调函数的this保持一致
canRun = true;
}, wait);
}
}
复制代码
咱们指定了一个时间间隔500ms,规定500ms内滚动事件回调函数只能执行一次。函数节流的实现要点是,使用闭包存储是否可执行标记,若是可执行则设置一个延迟函数,在延迟函数中重置可执行标记。app
实现dom
let count = 0;
$(document).scroll(deBounce(function () {
console.log(`触发了${++count}次!`);
}, 500));
function deBounce(fn, interval) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() =>{
fn.apply(this, arguments);
}, interval);
}
}
复制代码
咱们指定一个时间间隔500ms,规定滚动事件的回调函数,只有在事件触发的间隔大于500ms时回调函数才执行。函数防抖的实现要点是,使用闭包存储一个延迟函数编号(便于清空延迟函数),在事件触发的时候,清空这个延迟函数,而且设置新的延迟函数。函数
上文函数节流和函数防抖的实现中,调用fn的时候都是用的fn.apply(this, arguments)调用,而不是fn()直接调用。主要缘由是为了fn函数内的this与本来的事件回调函数绑定的this保持一致。 setTimeout()调用的代码运行在与所在函数彻底分离的执行环境上。这会致使,这些代码中包含的 this 关键字会指向 window (或全局)对象。所以在setTimeout中使用箭头函数(箭头的this绑定的是当前的词法做用域)此时的词法做用域为scroll事件回调函数中绑定的this(jquery中强制this指向dom元素),再将fn函数内的this绑定为这个this。咱们以函数防抖为例看看这两种的区别。学习
$(document).scroll(deBounce(function () {
console.log(this); //#document
}, 500));
function deBounce(fn, interval) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() =>{
fn.apply(this, arguments);
}, interval);
}
}
复制代码
$(document).scroll(deBounce(function () {
console.log(this); //Window
}, 500));
function deBounce(fn, interval) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() =>{
fn();
}, interval);
}
}
复制代码
$(document).scroll(deBounce(function () {
console.log(this); //Window
}, 500));
function deBounce(fn, interval) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
fn.apply(this, arguments);
}, interval);
}
}
复制代码
但愿本文对你们有所帮助,互相学习,一块儿提升。转载请注明原帖。优化