需要近期研究的项目JS

JS防抖小知识

2021-12-07  本文已影响0人  周星星的学习笔记

我们在做类似搜索框输入的时候,如果是即时搜索(只要输入框内容有变化就触发搜索请求),一般情况下没有什么大问题,但是无形中多出了很多无用的请求,如何能做到搜索我们想要的关键字呢?这个时候就要用到防抖的知识了。

一、一般的做法

1.代码示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input id="searchInput" type="text" />
    <script>
        const inputDom = document.getElementById('searchInput');
        inputDom.addEventListener('input',() => {
            console.log('发送搜索请求');
        })
    </script>
</body>
</html>

2.效果(每输入一次字符就会发送一次请求)

效果

二、防抖处理后

1.代码示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input id="searchInput" type="text" />
    <script>
        const inputDom = document.getElementById('searchInput');
        function debounce(fn, delay) {
            let timer = null;
            return function () {
                if (timer) {
                    clearTimeout(timer)
                }
                timer = setTimeout(() => {
                    fn();
                }, delay)
            }
        }
        inputDom.addEventListener('input', debounce(() => {
            console.log('发送搜索请求');
        }, 500))
    </script>
</body>
</html>

2.效果(快速输入只会有一次请求)

效果

三、备注

参考来源

上一篇下一篇

猜你喜欢

热点阅读