节流函数就是在单位时间(10s)内随便触发多少次,只要过了单位时间(10s)就会执行一次。
应用场景是:用户在输入框内疯狂输入字符串,每经过单位时间就会向后端发起请求查询数据库。
节流函数有两种实现方式:1.定时器 2.计算时间差
时间差实现
function throttle(fn, delay) {
let previous = 0;
// 使用闭包返回一个函数并且用到闭包函数外面的变量previous
return function() {
let args = arguments;
let now = new Date();
if(now - previous > delay) {
fn.apply(this, args);
previous = now;
}
}
}
// test测试函数
function testThrottle(content) {
console.log( content);
console.log("2222");
}
let testThrottleFn = throttle(testThrottle, 5000); // 节流函数
console.log(testThrottleFn)//此处注意看testThrottleFn的输出 是return返回的那个匿名函数
//下面这个用setInterval调用testThrottleFn和在document.onmousemove里面执行 效果是一样的 大家可酌情选择
//但是大家要注意setInterval传参的时候的写法
// setInterval("testThrottleFn('11211throttle')", 1000)
document.onmousemove = function () {
testThrottleFn('1111throttle'); // 给节流函数传参
}
最外面那个函数是用来做闭包的, 里面那个匿名函数才是真正做节流的
testThrottleFn 指向的是上面return的那个匿名函数
定时器实现
function throttle(fn,delay) {
let timeout
return function() {
let args = arguments;//注意如果要传参的话 这句不能省略
if(!timeout){
timeout = setTimeout(()=>{
timeout = null;
fn.apply(this,args)
},delay)
}
}
}
// test
function testThrottle(content) {
console.log(content);
console.log("2222");
}
let testThrottleFn = throttle(testThrottle, 5000); // 节流函数
console.log(testThrottleFn)
document.onmousemove = function () {
testThrottleFn('1111throttle'); // 给节流函数传参
}
这是我自己对节流函数的理解
如果大家有不同意见 欢迎大家评论区互相交流学习