防抖&节流

104 阅读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 type="text" placeholder="请输入搜索内容">
    <script src="./lib/axios.js"></script>
    <script>
        let timeId
        let bn = document.querySelector('input')
        bn.addEventListener('input', function() {
            // 清楚上一次的延时器
            clearTimeout(timeId)
​
            // 如果输入框没有值,退出
            if (bn.value == '' || bn.value.length == 1) {
                return
            }
​
            // 设置防抖延时器,
            timeId = setTimeout(function() {
                // 发起请求
                axios({
                    method: 'get',
                    url: 'http://www.itcbc.com:3006/api/getbooks',
                    params: {
                        bookname: bn.value
                    }
                }).then(res => {
                    console.log(res);
                })
            }, 1000)
        })
    </script>
</body></html>

节流:

节流:单位时间内,频繁触发同一个操作,只会触发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>
    <link rel="stylesheet" href="./lib/bootstrap-v4.6.0.css">
    <link rel="stylesheet" href="./lib/throttle.css">
</head><body>
​
    <!-- 外层的盒子 -->
    <div class="box">
        <img src="./img/photo.gif" class="photo" alt="">
    </div>
​
    <!-- 发射的按钮 -->
    <button class="btn btn-primary btn-fire">Fire</button>
​
    <script src="./lib/jquery-v3.6.0.js"></script>
    <script>
        $(function() {
            // 先声明一个变量
            let isok = true
            $('.btn-fire').on('click', function() {
                // 如果点击,isok未false
                if (!isok) return
                isok = false
​
                const newBall = $('<img src="./img/bullet.png" class="ball" alt="" />')
​
                $('.box').append(newBall)
​
                newBall.animate({
                    left: '95%'
                }, 1000, 'linear', function() {
​
                    $(this).remove()
                        // 执行完操作,isok为true
                    isok = true
                })
            })
        })
    </script>
</body></html>

\