1.什么是节流?
如果频繁的点击登录按钮,那么就会一直提交,一直请求数据。节流之后,假设是1s,那么只会1s响应一次用户的登录请求。
节流函数如下:函数主要分为两部分,一部分计算当前时间,之前时间。一部分用apply绑定this.
原版解说:
第一种是用时间戳来判断是否已到执行时间,记录上次执行的时间戳,然后每次触发事件执行回调,回调中判断当前时间戳距离上次执行时间戳的间隔是否已经达到时间差(Xms) ,如果是则执行,并更新上次执行的时间戳,如此循环。
const throttle=(fn,wait=50)=>{
let previous=0;
return function(...args)
{
let now=+new Date();
if(now-previous>wait)
{
previous=now;
fn.apply(this,args)
} }}
const betterFn= throttle(() => console.log('fn 函数执行了'), 1000)
setInterval(betterFn,10)
2.什么是防抖?
假设用户一直不停的点击登录,那么不会点一次就请求一次数据,而会在最后一次请求数据时候再进行响应。
此时「上车的乘客」就是我们频繁操作事件而不断涌入的回调任务;「1 分钟」就是计时器,它是司机决定「关门」的依据,如果有新的「乘客」上车,将清零并重新计时;「关门」就是最后需要执行的函数
函数要点为缓存定时器id,如果触发时存在这个定时器id,就清除,从新再开始定时。
function debounce(fn, wait = 50) {
let timer = null
return function(...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, wait)
}}
const betterFn = debounce(() => console.log('fn 防抖执行了'), 1000)
document.addEventListener('scroll', betterFn)