什么是javascript函数节流?
javascript函数节流就是针对调用频率高的函数,通过设置定时器,使其在执行后间隔一段时间,才进行下一次的执行,避免重复频繁的调用导致的浏览器性能以及ajax重复调用问题。
函数节流的基本应用场景:onresize,scroll,mousemove ,mousehover等事件回调函数的无间断执行。一般实现是通过setTimeout定时器,通过设置缓冲时间,在第一次调用时,创建定时器,并在定时时间结束调用。第二次调用时,会清除前一个定时器并设置新的定时器。如果这时前一个定时器暂未执行,则将其替换为新的定时器。
// 等到滚动条停止之后才调用
// 处理的函数
const theCall= () =>{
console.log("函数调用");
}
// 定时器函数
const fn = (method, time = 300) => {
clearTimeout(method.tId)
method.tId = setTimeout(function(){
method();
}, time);
}
// 事件监听
window.onscroll = () =>{
console.log("滚动条滑动时触发");
fn(theCall, 300);
}
// 优化:滑动的时候,隔一段时间,不管有没停止滑动,都要执行处理逻辑
const theCall = (text) => {
console.log("函数调用",text);
}
/**
* [@param] fn function 执行函数
* [@param] time number 延时时间
* [@param] mustRun number 隔断时间后,自动执行
*/
const throttle = (fn, time = 300, mustRun = 1000) =>{
let timer = null;
let previous = null;// 存储上一次的时间
return () =>{
const now = new Date();
if (!previous ) previous = now;
const timeDifference = now - previous;
if(mustRun && timeDifference >= mustRun){
fn('隔断时间后,自动执行');
previous = now;
}else{
clearTimeout(timer);
timer = setTimeout(()=>{
fn('停止,延时执行');
}, time);
}
}
}
window.onscroll = throttle(theCall, 300, 1000);