JS 防抖节流简单应用

1、防抖(debounce):触发高频事件后 n 秒内函数只会执行一次,如果 n 秒内高频事件再次被触发,则重新计算时间

举例:就好像在百度搜索时,每次输入之后都有联想词弹出,这个控制联想词的方法就不可能是输入框内容一改变就触发的,他一定是当你结束输入一段时间之后才会触发。

节流(thorttle):高频事件触发,但在 n 秒内只会执行一次,所以节流会稀释函数的执行频率

举例:预定一个函数只有在大于等于执行周期时才执行,周期内调用不执行。就好像你在淘宝抢购某一件限量热卖商品时,你不断点刷新点购买,可是总有一段时间你点上是没有效果,这里就用到了节流,就是怕点的太快导致系统出现bug。

2、区别:防抖动是将多次执行变为最后一次执行,节流是将多次执行变成每隔一段时间执行。

<!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="input" type="text">
    <button id="button">click</button>
    <script>
        function debounce(fun, delay) {
            let timer;
            return function (args) {
                clearInterval(timer)
                timer = setTimeout(() => {
                    fun(args)
                }, delay);
            }
        }
        function inputFun(value) {
            console.log(`你的输出结果是${value}`)
        }
        const input = document.getElementById("input")
        const deboundInput = debounce(inputFun, 500)
        input.addEventListener('keyup', function (e) {
            deboundInput(e.target.value)
        })
        function throttle(func, wait) {
            let timerOut;
            return function () {
                if (!timerOut) {
                    timerOut = setTimeout(function () {
                        timerOut = null;
                        func()
                    }, wait)
                }
            }
        }
        function handle() {
            console.log(Math.random())
        }
        document.getElementById("button").onclick = throttle(handle, 2000)
    </script>

</body>

</html>
posted @ 2021-03-07 16:14  abcdefgab  阅读(73)  评论(0)    收藏  举报