手写封装防抖debounce

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>封装防抖debounce</title>
    </head>
    <body>
        <input type="text" id="input1">
    </body>
</html>

<script type="text/javascript">
    // 封装防抖
    function debounce(fn, delay = 500) {
        //timer 是闭包中的
        let timer = null
        
        return function () {
            if(timer) {
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                fn.apply(this, arguments)
                timer = null
            },delay)
        }
    }
    
    
    const input1 = document.getElementById('input1')
    input1.addEventListener('keyup', debounce(function () {
        console.log(input1.value)
    }),600)
</script>

 

posted @ 2021-11-04 10:04  大熊丨rapper  阅读(62)  评论(0)    收藏  举报