js防抖快速记忆

218 阅读1分钟

核心记忆点:防抖函数当做事件的回调,在闭包中清除定时器。

<!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>
    <button id="btn">提交</button>
    <script>
        var oBtn = document.getElementById("btn");
        oBtn.onclick = deBounce();
        function show() {
            setTimeout(function(){
                console.log("模拟的ajax执行了!");
            },3000)
        }
        function deBounce(){
            var timer = null;
            return function(){
                clearTimeout(timer);
                timer = setTimeout(function(){
                    show();
                },800)
            }     
        }

    </script>
</body>
</html>