节流函数
在time时间内,即使触发了函数fn很多次,但通过节流函数的包装,可以让fn只执行最早的一次。
代码实现
// 利用date实现
let throttle_date = function(fn,time){
let prevTime = 0;
return function(...args){
let currentTime = Date.now();
if(currentTime - prevTime >= time) {
fn(...args);
prevTime = currentTime;
}
}
}
// 测试代码
function getMsg(number){
console.log(Math.random()*number);
}
window.addEventListener('scroll',throttle_setTimeout(getMsg,1000,10))
防抖函数
在time时间内,即使触发了函数fn很多次,但通过防抖函数的包装,可以让fn只执行最后的一次。 代码实现
let debounce = function(fn,time){
let timer = null;
return function(){
if(timer !== null) {
clearTimeout(timer);
}
timer = setTimeout((...args)=>{
fn(...args);
},time);
}
}
function getMsg(number){
console.log(Math.random());
}
window.addEventListener('scroll',debounce(getMsg,1000))