js实现函数节流

96 阅读1分钟

问题:什么事节流?

节流意思是函数在n秒不管请求了多少次,只执行了一次。

实现

<!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
            let bool = true
            return function () {
                if (!bool) return
                bool = false
                if (timeout) {
                clearTimeout(timeout)
                }
                setTimeout(() => {     
                    fn.apply(this,arguments)
                    bool = true
                }, 1500)
            }
        }
        /**
         * 执行函数
         */
        function sayHi () {
            console.dir('节流成功')
        }
        const inp = document.getElementById('input')
        inp.addEventListener('input', debounce(sayHi))
    </script>
</body>
</html>

结果

image.png

如图,在1.5秒输入123456 函数只执行了一次