js实现函数防抖

76 阅读1分钟

问题:什么是防抖?

触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。

js实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" id='input'>
    <script>
         /**
         * 防抖函数
         * @param  {Function} fn 回调函数
         */
        function debounce (fn) {
            const timeout = null
            return function () {
                if (timeout) {
                  clearTimeout(timeout)
                }
                setTimeout(() => {     
                    fn.apply(this,arguments)
                }, 500)
            }
        }
        /**
         * 执行函数
         */
        function sayHi () {
            console.dir('防抖成功')
        }
        const inp = document.getElementById('input')
        inp.addEventListener('input', debounce(sayHi))

    </script>
</body>
</html>

效果

image.png