Encapsulate the debounce function

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
    
    
            margin: 20px auto;
            width: 500px;
            height: 500px;
            border: 1px solid red;
        }
    </style>
</head>

<body>
    <div id="dv"></div>
    <script>
        const dv = document.getElementById('dv')

        /* 
       封装防抖函数
       */
        function debounce(callBack, time) {
    
    
            // callBack: 传入的回调函数
            // time: 定时器的第二个参数(多长时间触发)
            // 存放定时器的Id
            let timer = null
            return function () {
    
    
                // 通过定时器Id清除定时器
                clearTimeout(timer)
                // 将定时器的返回值 定时器Id 存到 timer 中
                timer = setTimeout(() => {
    
    
                    // 通过 apply 改变传入的回调函数 callBack 的 this 指向
                    // 通过 arguments 拿到外层函数的事件对象(箭头函数没有 this 指向)
                    // 注意:事件处理函数只能有一个形参(拿到事件对象),
                    // 如果要传多个参数,方法:在外面封装一个函数,在事件处理函数中调用
                    callBack.apply(this, arguments)
                }, time)
            }
        }

        dv.onmousemove = debounce(function (e) {
    
    
            this.innerHTML = `x的坐标为${
      
      e.pageX},y的坐标为${
      
      e.pageY}`
        }, 100)

    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/weixin_46611729/article/details/111146225