通过具体的 Demo 来分别先说下「节流」和「防抖」。
//函数节流
function throttle(fn, delay) {
//先定义一个 最后的时间戳
let lastTimer = null;
return function(){
//获取当前时间戳
let nowTimer = Date.now();
//如果最后时间没有被赋值过,并且当前时间比最后时间大于 delay 的毫秒数,则执行
if( !lastTimer || nowTimer - lastTimer > delay ){
lastTimer = nowTimer;//赋值 最后时间戳
fn.apply(this,arguments);//给定 this,然后提供 arguments 参数
}
}
};
<div id=\\\"mouseDemo\\\" class=\\\"mouseDemo\\\"></div>
let mouseDemo = document.getElementById(\\\'mouseDemo\\\');
mouseDemo.addEventListener(\\\'mousedown\\\', event => {
let startX = event.clientX;
let move = throttle(event=>{
console.log(event)
},100);
let up = () => {
document.removeEventListener(\\\'mousemove\\\', move);
document.removeEventListener(\\\'mouseup\\\', up);
}
document.addEventListener(\\\'mousemove\\\', move);
document.addEventListener(\\\'mouseup\\\', up)
})
//函数防抖
let throttle = function(fn, delay) {
let timer = null;//先定义一个参数,做为 setTimeout 定时器的编号
return function(){
clearTimeout(timer);//无论如何,先清除定时器编号 timer
timer = setTimeout(()=>{
//改变this,并提供参数
fn.apply(this,arguments)
},delay)
}
};
let myFunc = ()=>{
console.log(1);
}
//当浏览器窗口发生变化时,执行函数;
window.onresize = throttle(myFunc,200);
//window.onresize = myFunc(); //对比代码
两个案例,可以查看 Git 仓库获取:
https://github.com/cuishunbiao/Frontend-02-Template/tree/master/week13/jsx/extend
原创文章,作者:小道研究,如若转载,请注明出处:https://www.sudun.com/ask/34502.html