防抖和节流
函数防抖 debounce:用户一直触发事件,事件处理函数是不会执行的,直到用户在指定的时间内不在触发该事件,则执行一次事件处理程序(防抖意味着事件处理程序只会执行性一次)
函数节流 throttle:用户一直触发事件,事件处理函数会每间隔指定的时间后执行一次, 在指定的时间内不会反复执行;(节流意味着事件处理程序每间隔指定的时间执行一次)
防抖和节流的区别:防抖是将多次执行变为最后一次执行,节流是将多次执行变为每隔一段时间执行
防抖和节流的实现方式: 计时器和时间戳 (为了防止变量污染,通过闭包的形式实现功能)
参考网址: https://www.cnblogs.com/youma/p/10559331.html
<script>
// 函数防抖
/**
* @author: xxx
* @time 2021-2-2 18:19:30
* @params {function} fn
* @params {number} delay
*
*/
function debounce(fn, delay) {
// 提前声明一个计时器, 赋值为null
let timer = null;
return function () {
// if(!timer){
// timer = setTimeout(fn, delay)
// }else{
// clearTimeout(timer);
// timer = setTimeout(fn, delay)
// }
// 防抖: 关键点在于清除计时器的节点
if (timer) {
clearTimeout(timer);
}
// timer = setTimeout(fn, delay)
// 考虑到this指向和传参的问题
let that = this;
let args = arguments;
timer = setTimeout(function () {
fn.apply(that, args)
}, delay)
}
}
// 节流函数 : ========= 时间戳
/* function throttle(fn, delay){
// 起点的时间
let start = Date.now();
return function(){
let that = this;
let args = arguments;
// 获取当前时间,通过 当前时间 - 起点时间 = 时间差,,, 判断 时间差和 delay的关系
let diff = Date.now() - start
if(diff > delay){
fn.apply(that, arguments)
// 事件处理程序执行一次后,需要重新计时
start = Date.now();
}
}
} */
// 节流函数 : 计时器实现 + 变量实现
/* function throttle(fn, delay) {
let timer = null;
// 通过一个变量控制事件处理程序的执行频率
let flag = true;
return function () {
let that = this;
let args = arguments;
// 进来 如果flag = true
console.log(flag);
// 在指定的时间间隔内,flag = false; 指定的时间间隔到达后,flag = true ;
if (!flag) {
// 终止代码执行
return;
}
flag = false;
if (!flag) {
timer = setTimeout(function () {
fn.apply(that, args);
flag = true;
}, delay)
}
}
} */
// 节流 : 计时器实现
/* function throttle(fn, delay) {
let timer = null;
return function () {
let that = this;
let args = arguments;
// 进来 如果flag = true
if (!timer) {
timer = setTimeout(function () {
fn.apply(that, args);
timer = null;
}, delay)
}
}
} */
// 节流函数: 计时器 + 时间戳
function throttle(fn, delay) {
let timer = null;
let start = Date.now();
// timer = setTimeout(function () {
// fn.apply(this, arguments);
// },0)
return function () {
let that = this;
let args = arguments;
let diff = Date.now() - start;
if (diff > delay) {
timer = setTimeout(function () {
fn.apply(that, args);
timer = null;
}, delay)
start = Date.now();
}
}
}
// 真正的时间处理程序
function print() {
console.log('hello world');
}
// window.onscroll = print;
// window.onscroll = debounce(print, 2000);
window.onscroll = throttle(print, 2000);
/* window.onscroll = function () {
// 考虑到this指向和传参的问题
let that = this;
let args = arguments;
console.log(222222222);
if(!timer){
timer = setTimeout(fn, delay)
}
} */
</script>