性能优化——函数防抖

版权声明:感谢支持原创 https://blog.csdn.net/lilele0227/article/details/87867500

场景

  • 搜索框,根据输入内容做模糊匹配,输入的时候不出现结果,输完以后得到匹配的结果
  • 用户注册时候的手机号码验证和邮箱验证了,只有等用户输入完毕后,前端才需要检查格式是否正确

概念

  以大学考试为例,如果一次考试中没及格,那么就需要重新考试。函数防抖则是实现类似的效果——事件被触发n秒后再执行回调(考试及格),如果在这n秒内又被触发(不及格),则重新计时

实现

  没有代码的博客都是耍流氓,我们以keyup事件为例来看看函数防抖。

  • 未优化代码
<html>
<meta charset="UTF-8">
<head>
    <title>test</title>
</head>
<body>
    <input id="app" type="text" onKeyDown="keydown()">
</body>
<script>

    function ajax(){
        console.log("我发送了一次请求");
    }

    function keydown(){
        ajax();
    }

</script>
</html>

运行的结果如图:

在这里插入图片描述

  只要按下键盘,就会触发一次ajax请求。不仅浪费资源,而且用户体验也不好,用户是在输出完整的字符后,才会请求。进行一下优化:

  • 函数防抖优化后的代码
<html>
<meta charset="UTF-8">
<head>
    <title>test</title>
</head>
<body>
    <input id="app" type="text" onKeyDown="keydown()">
</body>
<script>

    function ajax(){
        console.log("我发送了一次请求");
    }

    function debounce(func, delay){
        return function (args) {
            let that = this
            let _args = args
            clearTimeout(func.id)
            func.id = setTimeout(function () {
                func.call(that, _args)
            }, delay)
        }
    }

    let debounceAjax = debounce(ajax, 1000)

    function keydown(){
        debounceAjax();
    }

</script>
</html>

  运行结果如图:

在这里插入图片描述

  我们规定每1000ms内触发keydown事件,则重新计算触发事件,否则执行keydown函数,执行一次请求。

猜你喜欢

转载自blog.csdn.net/lilele0227/article/details/87867500
今日推荐