js高阶函数-节流&防抖函数

一、前言

    防抖函数主要用于输入框调用频繁接口等业务场景。

    节流函数主要用于需要限流接口调用的业务场景。    

二、正文

    节流函数

//函数节流
function throttle(fn, delay = 300) {
            let timer; //定时器
            let firstTime = true;//是否第一次调用
            return function () {
                let args = arguments;
                let _this = this;
                //如果第一次执行,不需要延迟
                if(firstTime){
                    fn.apply(_this,args);
                    return firstTime =false;
                }
                //如果定时器还在,说明上一次调用还没有完成
                if(timer){
                    return false;
                }
                //延迟1段事件执行
                timer = setTimeout(function () {
                    clearTimeout(timer);//清理定时器
                    timer =null;//闭包内存释放
                    fn.apply(_this,args);//返回的新函数、参数借用源函数执行
                },delay)
            }
        }
//调用,例如1个按钮,在1秒内被重复点击,会延时触发
document.getElementById("btn").onclick = throttle(function () {
             console.log(1)
         },1000)

    //防抖函数

function debounce(fn, delay = 300) {
            let timer;
            return function () {
                let _this = this;
                let arg = arguments;

                if(timer){
                    clearTimeout(timer);
                    return timer = null;
                }

                timer = setTimeout(()=>{
                    timer = null;
                    fn.apply(_this,arg)
                },delay)
            }
        }

        document.getElementById("btn").onclick = debounce(function () {
            console.log("click")
        })

 

三、总结

    通过使用闭包,我们可以将变量保存在内存中,在变量执行完后,我们可以手动释放内存,即将 变量赋值为null,防止内存泄漏。

    故,大多数面试者问造成内存泄漏的原因,其实是担心你在使用变量后,没有在闭包中手动释放。

你可能感兴趣的:(javascipt,闭包,高阶函数,节流,防抖,javascript)