其他分享
首页 > 其他分享> > 我的封装节流

我的封装节流

作者:互联网

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<input type="text" id="input_wrapper">
<script>
    let oInput = document.getElementById("input_wrapper");
    oInput.addEventListener("input", throttle(function (e) {
        console.log(e);
    }, 1000))

    function throttle(fn, delayTime) {
        let flag = true
        let timerId = null
        return function () {
            // 因为throttle一开始就执行了,那么就是返回了这个函数,而这个函数就要接收e,或者其他参数
            // 所以在这边接收是没毛病的,然后this,也就指向了元素(拿addEventListener来说)
            let args = arguments
            let event = this
            if (!flag) return;
            flag = false
            timerId && clearTimeout(timerId)
            timerId = setTimeout(() => {
                fn.apply(event, args)
                flag = true
            }, delayTime || 1000)
        }
    }
</script>
</body>
</html>

标签:function,封装,节流,flag,let,oInput,throttle,timerId
来源: https://blog.csdn.net/weixin_49274461/article/details/123193553