JS 防抖节流简单应用

时间:2021-03-08 14:01:59   收藏:0   阅读:0
<!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>
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!