函数防抖,就是指触发事件后,在 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
如果我们在 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)
}
}
}
连续的事件,只需触发一次的回调场景有:
间隔一段时间执行一次回调的场景有:
参考链接:
JavaScript专题之跟着underscore学防抖
JavaScript专题之跟着 underscore 学节流