博客园

super.hill

记录搬砖中遇到的坑,欢迎批评指导!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
//节流 设置的时间内只能调用一次
//节流函数 写法1 时间差版本
function
throttle(method, delay) { let timer, args = arguments, start; return function fn() { let self = this; let now = Date.now(); if(!start){ start = now; } if(timer){ clearTimeout(timer); } if(now - start >= delay){ method.apply(self, args); start = now; }else { timer = setTimeout(function () { console.log(args,'args') fn.apply(self, args); }, delay); } } }

//节流函数 写法2 定时器版本
function throttle(fn,delay) {
    var executed = false
    return function () {
        if(executed) return;
        var that = this;
        
        fn.apply(that,...arguments)
        executed = true
        
        setTimeout(() => {
            executed = false;
        }, delay);
    }
}
// 防抖函数
function
debounce(method,delay){ let _delay = delay || 0; let timer = null; return function(){ let args = arguments; timer && clearTimeout(timer); timer = setTimeout(()=>{ method.apply(this,args) },_delay) } }

 这里用的apply和call主要改变this指向。

posted on 2019-06-20 20:38  超岭  阅读(132)  评论(0)    收藏  举报
博客园