js 防抖和节流,封装成函数

<!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="s1" style="width: 100px;height: 100px;background-color: pink;">
</button>
<button id="s2" style="width: 100px;height: 100px;background-color: pink;">
</button>
</body>

<script>
    // 防抖:同一个事件在某个时间段内被触发多次,只执行最后一次事件
    // 节流:同一个事件在某个时间段内被触发多次,在这个时间段内只执行一次
    let count = 0
    let s1 = document.getElementById("s1")
    //debounce 防抖

    debounce = function (func, wait) {
        //由于debounce是这样被调用 s1.onmousemove = debounce(add,300)
        //所以let timeout=null只在加载时执行一次
        let timeout = null
        console.log("hhh")
        //需要return function (),否则下面的 s1.onmousemove = debounce(add) 在页面加载时会直接调用
        return () => {
            // console.log("timeout"+timeout)
            if (timeout) {
                clearTimeout(timeout)
            }
            timeout = setTimeout(() => {
                func.apply(this)
                //func()也可以
            }, wait)
        }
    }
    add = () => {
        console.log(this)
        s1.innerText = count
        count++;
    }

    //鼠标在s1对应的节点上滑动时触发
    s1.onmousemove = debounce(add, 300)
    // throttle节流

    let s2 = document.getElementById("s2")

    throttle = (func, wait) => {
        let flag = true
        return () => {
            if (flag) {
                setTimeout(() => {
                    func()
                    flag = true
                }, wait);
                flag = false
            }
        }
    }
    s2.onmousemove = throttle(add, 1000)
</script>
</html>

猜你喜欢

转载自www.cnblogs.com/yloved/p/13167201.html
今日推荐