函数防抖和节流




    
    
    
    防抖和节流


    

debonuce

throttle

        const input = document.getElementById('input')
        //函数防抖(debounce) 
        //在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
        function debonuce(delay){
            let timer;
            //闭包 内部函数被保留在了外部
            return function(value){
                clearTimeout(timer);
                timer = setTimeout(function(){
                    console.log(value)
                }, delay)
            }
        }
        var debonuceFunc = debonuce(1000);
        input.addEventListener('keyup', function(e){
            debonuceFunc(e.target.value)
        });

        //函数节流(throttle)
        //一段时间内只做一件事情
        function throttle(func, wait){
            let timer = null;
            return function(value){
                if(!timer){
                    timer = setTimeout(function(){
                        func()
                        //执行完就置为null
                        timer = null
                    }, wait)
                }
            }
        }

        const btn = document.getElementById('btn');
        function handle(){
            console.log(Math.random());
        };
        btn.onclick = throttle(handle, 2000);

你可能感兴趣的:(函数防抖和节流)