首页 > Web开发 > 详细

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

时间:2020-06-20 09:08:54      阅读:72      评论:0      收藏:0      [点我收藏+]
<!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>

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

原文:https://www.cnblogs.com/yloved/p/13167201.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!