js 函数节流和防抖

        //节流 在规定时间内 只触发第一次
        function throttle (fn,delay=1000) {
            var flag = 0;
            return function(){
                var nowTime = Date.now();
                if(nowTime-flag>delay){
                    fn.apply(this,arguments);
                    flag = nowTime
                }
            }
        }
        //防抖 在规定时间内只触发最后一次
        function debounce(fn,delay=1000){
            var timer = null;
            return function(){
                clearTimeout(timer);
                timer = setTimeout(() => {
                    fn.call(this)
                }, delay);
            }
        }
        document.onscroll = throttle(function(){
                console.log('---'+Date.now());
        },1000)

        var dom = document.querySelectorAll('#btn');
        dom[0].onclick = debounce(function(){
                console.log('---'+Date.now());
        },1000)

 

posted @ 2020-04-10 17:41  十方故里  阅读(227)  评论(0)    收藏  举报