函数节流

什么是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);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值