防抖,节流(2种)

150 阅读1分钟

防抖,可以用于避免用户短时间多次点击登录、发短信等按钮,发送了多次请求,或调整浏览器窗口大小时,resize次数过于频繁,造成计算过多。也是项目中需要优化的一点,

function debounce(fn, delay) {
            let timer = null
            return function () {
                let context = this
                let args = arguments
                clearTimeout(timer)
                timer = setTimeout(function () {
                    fn.call(context, args) 
                },delay)
            }
        }

节流,在短时间内只能触发一次,用于针对优化一些使用频率较高的函数

   function throttle(fn, delay) {
            let timer = null
            return function () {
                let context = this
                let args = arguments
                if (!timer) {
                    timer = setTimeout(function () {
                        fn.call(context, args) 
                        timer = null
                    }, delay)
                }
            }
        }
        
function throttle(fn, delay) {
            let prev = 0
            return function () {
                let now = new Date();
                if (now - prev > delay) {
                    fn()
                    prev = now;               
                }
            }

        }