函数防抖和节流

1. 函数防抖(事件频繁触发,在特定时间内,函数只被触发一次, 如果在特定时间内,不断被触发,则会重新计算时间)

   

   <button id="btn1">防抖</button>

 // 防抖
        function getData() {
            console.log(1111);
        }
        const debounce = (fn, delay = 300) => {
            let timer = null;
            return (...args) => {
                if (timer) {
                    clearTimeout(timer)
                }
                timer = setTimeout(() => {
                    fn.apply(this, args)
                }, delay)
            }
        }
        let btn1 = document.getElementById('btn1')
        btn1.addEventListener('click', debounce(getData, 500))
 
 2. 函数节流 (事件频繁被触发, 在特定时间内,只触发一次, 若在单位时间内, 触发多次, 只要一次生效)
     
 <input id="search" type="text" name="search">
    
// 节流
        function queryData(text) {
           console.log('搜索' + text);
        }
        const throttle = (fn, delay = 300) => {
            let flag = false;
            return (...arg) => {
                if (flag) return;
                flag = true;
                setTimeout(() => {
                    fn.apply(this, arg);
                    flag = false;
                }, delay);
            }
        }
        const search = document.getElementById('search');
        const throttleFn = throttle(queryData, 500);
        search.addEventListener('keyup', (event) => {
            throttleFn(event.target.value)
        })

若有不对的地方, 请指出...
原文地址:https://www.cnblogs.com/big--Bear/p/12165575.html