防抖和节流区别有哪些?应用场景有哪些?原理是什么?原生怎么实现?

浏览器的一些事件,如:resize,scroll,keydown,keyup,keypress,mousemove等。这些事件触发频率太过频繁,绑定在这些事件上的回调函数会不停的被调用。这样浏览器的目的是为了保证信息的一致性,而对于我们来说就是一种资源的浪费了。
所以说,防抖和节流严格算起来应该属于性能优化的知识

概念:防抖就是固定时间内不会执行代码逻辑,如果触发事件就会在n秒后执行,如果重复触发,就会延迟n秒,直到触发得事件结束时,再在n秒后执行代码
节流就是当你触发事件得时候,代码逻辑是有一个固定得时间去触发得

区别:在执行代码逻辑得时候,防抖会出现延迟,但是节流是不会出现延迟现象得,它是一个懂得时间观念得乖宝宝!

防抖:应用场景 :
在这里插入图片描述
原理:举个例子
但是以下我写得是mousemove事件
在这里插入图片描述
代码:

   <div class="box">

    </div>
        //  js代码:
        var index = 0;
        var box = document.querySelector('.box')

        function getAction(e) {
            console.log(this)  // 输出当前得this指向
            console.log(e)  // 输出当前得事件对象
            index++;
            box.innerHTML = index
        }
        getAction()
        //box.onmousemove = getAction  // getAction里面this指向dom e表示事件对象
        box.onmousemove = debounce(getAction, 2000)  // 对getAction防抖
        // getAction里面this指向window e undefined

        // func代表对那个高频函数进行防抖,wait代表防抖得时间间隔
        function debounce(func, wait) {
            var timeout;
            return function () {
                console.log(this)  // 指向dom div
                var _this = this   // 改变this得指向
                var args = arguments  // e就不会undefined了
                clearTimeout(timeout)
                timeout = setTimeout(function () {
                    func.apply(_this, args)   // this经过处理后this指向dom div
                }, wait)
            }
        }

节流
应用:上拉加载,滚动条
原理:

在这里插入图片描述
代码:

       <div class="box">

       </div>
       // js代码
        var index = 0;
        var box = document.querySelector('.box')
        function getAction(e) {
            index++;
            box.innerHTML = index
        }
        getAction()
        box.onmousemove = throttle(getAction, 2000)

        // 俩种实现方式 :时间戳 计时器
        function throttle(func, wait) {
            var timeout
            var _this;
            var args;


            return function () {
                _this = this;
                args = arguments
                if (!timeout) {
                    timeout = setTimeout(function () {
                        func.apply(_this, args)
                        timeout = null   // !!null = false
                    }, wait)
                }
            }
        }

猜你喜欢

转载自blog.csdn.net/lqlq54321/article/details/106503692