防抖与节流

86 阅读1分钟

防抖:

  • n秒内只要触发事件,就重新计时,事件处理的程序将永远不能被执行
  • 先清理计时器,再重新设置计时器

节流:

  • 事件被触发,n秒内只执行一次事件处理函数

input的keyup事件举例

    var input1 = document.getElementById('input1')

        function check() {
            var val = this.value

            if (val.length < 6) {
                console.log('Invaild length');
            } else {
                console.log('Success');
            }
        }

        input1.onkeyup = throttle(check, 1000)

     

        var box1 = document.getElementById('box1')

        let clickBounce = debounce(function () {
            console.log('1');
        }, 500)

封装公共的防抖函数


        function debounce(fn, time) {
            time = time || 500
            let t
            return function () {
                let _self = this
                let args = arguments

                // 存在定时器就清除
                if (t) {
                    clearTimeout(t)
                }
                var exec = !t

                t = setTimeout(() => {
                    t = null
                }, time)

                // 定时器不存在就执行fn
                if (exec) {
                    fn.apply(_self, args)
                }
            }
        }

封装公共的节流函数

    function throttle(fn, delay) {
            delay = delay || 500
            var t = null,
                begin = new Date().getTime()  // getTime() 返回距 1970 年 1 月 1 日之间的毫秒数:

            return function () {
                var _self = this
                var args = arguments
                cur = new Date().getTime()
                clearTimeout(t)
                if (cur - begin >= delay) {
                    fn.apply(_self, args)
                    begin = cur
                } else {
                    t = setTimeout(function () {
                        fn.apply(_self, args)
                    }, delay)
                }
            }

        }