美文网首页
函数节流

函数节流

作者: 我没叫阿 | 来源:发表于2021-07-06 19:19 被阅读0次

节流函数:当持续触发事件的时候,保证一段时间内只调用一次事件处理函数。

 <button id="btn">点击</button>
    <script>
        function throttle(fn, wait) {
            let timeOut
            return function () {
                // 如果timeout有值得话,就不执行
                if (!timeOut) {
                    timeOut = setTimeout(() => {
                        fn()
                        timeOut = null
                    }, wait);
                }
            }

        }

        function handle() {
            console.log('是否出现?');
        }
        document.getElementById('btn').onclick = throttle(handle, 2000)
    </script>

相关文章

网友评论

      本文标题:函数节流

      本文链接:https://www.haomeiwen.com/subject/rvagultx.html