防抖
防抖是将多次执行变为最后一次执行,节流是将多次执行变为每隔一段时间执行
/** 滚动完后,多少秒执行一次* 通过 锁 和 闭包思路解决*/// 不防抖 只要滚动就执行window.addEventListener('scroll', () => {console.log(1);});// 滚动防抖function debounce(fun, time) {let timeout = null;return function () {if (timeout !== null) {clearTimeout(timeout)}timeout = setTimeout(fun, time)}}// 处理函数function handle() {console.log(Math.random());}// 滚动事件window.addEventListener('scroll', debounce(handle, 10000))
节流
防抖是将多次执行变为最后一次执行,节流是将多次执行变为每隔一段时间执行
时间戳节流
let throttle = function(fun,delay){
let prev = Date.now() // 时间戳 记录滚动钱的时间戳
return function (){
let _this =this; // 保存this
var args = arguments; // 保存 arguments
let now = Date.now() // 时间戳
if(now - prev >= delay){ // 连续滚动的时间大于定好的时间
fun.apply(_this,args);
prev = Date.now();
}
}
}
function handle(){
console.log(Math.random());
}
window.addEventListener('scroll',throttle(handle,1000))
定时器节流
let throttle = function (fun,delay){
let timer = null;
return function (){
let _this = this;
let args = arguments;
if(!timer){
timer = setTimeout(function(){
fun.apply(_this,args);
timer = null;
},delay)
}
}
}
function handle(){
console.log(Math.random());
}
window.addEventListener('scroll',throttle(handle,1000))
定时器+时间戳
let throttle = function (fun, delay) {
let timer = null;
let startTime = Date.now(); // 开始时间
return function () {
let curTime = Date.now();
let remaining = delay - (curTime - startTime) // 剩余时间
let _this = this;
let args = arguments;
clearTimeout(timer);
if (remaining <= 0) {
fun.apply(_this, args);
startTime = Date.now();
} else {
timer = setTimeout(fun, remaining) // 取消当前并计算新的
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000))
