美文网首页
防抖 - debounce

防抖 - debounce

作者: Aniugel | 来源:发表于2019-03-31 13:59 被阅读0次

比如搜索框,用户在输入的时候使用change事件去调用搜索,如果用户每一次输入都去搜索的话,那得消耗多大的服务器资源,即使你的服务器资源很强大,也不带这么玩的。其中一种解决方案就是每次用户停止输入后,延迟超过1000ms时,才去搜索此时的String,这就是防抖。

  • 原理:将若干个函数调用合成为一次,并在给定时间过去之后仅被调用一次。
  • 代码实现:
    喜欢的用户可以点赞关注
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            height: 5000px;
        }
    </style>
</head>
<body>
    <script>
        function debounce(fn, wait) {
            var timeout = null;
            console.log('1')
            return function () {
                console.log('2')
                if (timeout !== null) {
                    clearTimeout(timeout);
                    console.log('3')
                }
                console.log('4')
                timeout = setTimeout(fn, wait);
            }
        }
        // 处理函数
        function handle() {
            console.log(Math.random());
        }
        // 滚动事件
        window.addEventListener('scroll', debounce(handle, 1000));
    </script>
</body>
</html>

相关文章

网友评论

      本文标题:防抖 - debounce

      本文链接:https://www.haomeiwen.com/subject/dzhvbqtx.html