Web性能优化(一)之防抖和节流

节流

概念:可以举个应用场景来理解,就是在搜索引擎执行过程中,我们每输入一个汉字后,搜索引擎自动执行ajax请求,但是键盘事件是通过字母触发而不是汉字,所以我们就可以固定频率来节约资源。

实现节流使用时间戳

 <section style="width: 1200px;height:400px;background: red" id="scry">

    </section>
    <script>
        var num = 0;

        function Fun() {
            console.log(num++);
        }
        var start = 0;

        function thow(func, time) {
            if (!start) {
                start = Date.now();
            }
            var delay = Date.now();
            if (delay - start > time) {
                func();
                start = 0;
            }
        }
        scry.onmousemove = function () {
            thow(Fun, 2000);
        }
    </script>

防抖

通过SetTimeout设置毫秒时间,在触发事件后,n秒内没有再次触发事件,处理函数才会执行,如果在这一段时间来到之前,又一次触发了事件,那就重新计时,举个例子:就是电梯5秒关门,有人进来后,重新计时5秒再关门。实际作用也是可以在搜索引擎里面用到,也就是只要你在输入内容的时候,都不会发型ajax请求。

实现代码

  <section style="width: 1200px;height:400px;background: red" id="scry"></section>
    <script>
        var num = 0;

        function Fun() {
            console.log(num++)
        };

        var timer = null;

        function thow(delay, fun) {
            clearTimeout(timer)
            timer = setTimeout(() => {
                fun();
            }, delay);
        }
        scry.onmousemove = function () {
            thow(2000, Fun)
        }
    </script>

总结:保证一段时间技结束后,才触发函数。如果中途又有事件,那么重新计时。

实际运用

节流:滚动变色,避免函数过多执行

防抖:搜索引擎

主要用于性能优化

猜你喜欢

转载自blog.csdn.net/qq_39125445/article/details/88366630