防抖 - debounce

2019-03-31  本文已影响0人  Aniugel

比如搜索框,用户在输入的时候使用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>
上一篇 下一篇

猜你喜欢

热点阅读