关于javascript:js防抖和节流

65次阅读

共计 677 个字符,预计需要花费 2 分钟才能阅读完成。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title> 防抖和节流 </title>
    </head>
    <body>
        <input type=""name="" id="input" value="" />
        <script>
            const debounce = function(fn, delay = 300) {
                let timer = null
                return function() {if (timer) clearTimeout(timer)
                    timer = setTimeout(() => {fn.apply(null, arguments)
                        timer = null
                    }, delay)
                }
            }
            
            const throttle = function(fn, delay = 300) {
                let timer = null
                return function() {if (timer) return
                    timer = setTimeout(() => {fn.apply(null, arguments)
                        timer = null
                    }, delay)
                }
            }
            // 防抖测试
            const input = document.getElementById('input')
            input.addEventListener('input', debounce((ev) => {console.log(ev.target.value)
            }, 500))
            // 节流测试
            window.addEventListener('resize', throttle((ev) => {console.log('resize', ev)
            }, 500))
        </script>
    </body>
</html>

正文完
 0