防抖函数和节流函数写法

为什么debounce 是返回一个 函数?  因为,这样可以解决闭包问题!!!!!

    function debounce(fn, delay, leading) {
            let timer = null
            leading = leading || false 
            return handle = function () {
                clearTimeout(timer);
                let _this = this
                let _arguments = arguments
                if (leading) {
                    let isCall
                    if (!timer) {
                        fn.apply(_this, _arguments)
                        isCall = true;
                    }
                    if (isCall) {
                        timer = setTimeout(() => {
                            isCall = false
                            fn.apply(this, arguments)
                        }, delay)
                    }

                }
                else {
                    timer = setTimeout(() => {
                        fn.apply(this, arguments)
                    }, delay)
                }
            }
        }
//   二个参数 防抖函数
        function debounce2(fn, delay) {
            let timer = null
            return function () {
                clearTimeout(timer)
                timer = setTimeout(() => { fn.apply(this, arguments) }, delay)
            }
        }

//   节流函数  定时器版
    function throttle(fn,time){
      let canUse = true ; // 设置一个开关
      return function(){
         if(!canUse ){ return false } // 如果开关已经关掉了就不用往下了
      // if(canUse) fn.apply(this,arguments)//fn放这里是立即执行
          canUse  = false  // 利用闭包刚进来的时候关闭开关
          setTimeout( ( ) => {
           fn.apply(this,arguments)//fn放这里是非立即执行,定时器结束才执行
           canUse = true // 执行完才打开开关
        },time)
    }



//   节流函数  时间戳版
        function throttle(fn, delay) {
            let lastTime = 0
            return function () {
                let nowTime = new Date().getTime()
                if (nowTime - lastTime > delay) {
                    fn.apply(this, arguments)
                    lastTime = nowTime
                }
            }
        }


        let aaa = function () {
            console.log(this)
        }
        var search = document.querySelector(".search");
        var _searchChange = jieliu(aaa, 1000);
        search.oninput = _searchChange;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值