函數防抖~ 如何解決用戶快速點擊的限制問題

函數防抖~

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button id="btn">按鈕</button>
    <script>
        function debounce(fn, delay) {
            // 記錄上一次的延遲時間
            var timer = null
            return function () {
                // 先清除第一次的定時器
                clearTimeout(timer)
                timer = setTimeout(function () {
                    fn.apply(this)
                }, delay)
            }
        }
        // btn.addEventListener('click', console.log('ok'))
        document.querySelector('#btn').onclick = debounce(function(){
            console.log('kk')
        },1000)
        console.log(debounce())
    </script>
</body>
</html>

具體能夠參考以上代碼~

相關文章
相關標籤/搜索