js中的节流

节流就像英雄的技能CD

举个例子:
    剑圣的R技能冷却CD中不能发技能,冷却CD结束后,想在哪个时间点放技能都可以
    节流的思想也是如此 开始的时候会执行fun函数一次,第二次执行fun函数与第一次fun函数执行的时间间隔必须不小于delay
   

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="#" rel="shortcut icon"/>
    <title>Title</title>
</head>
<body>
<form action="" class="example-form">
    <div>
        <label for="name">
            名称
        </label>
        <input autocomplete="off" class="input-ele" id="name" name="name" placeholder="please input your name"
               type="text">
    </div>
    <div>
        <label for="res">
            输入
        </label>
        <textarea class="input-ele" id="res" name="res" placeholder="这里是每一次输入的结果" readonly
                  style="width: 500px;height: 500px" type="multipart"></textarea>
    </div>
</form>

</body>
<script>
    window.onload = function () {
        const resEle = document.querySelector("#res");

        function changeOutputVal(value) {
            resEle.value += `\n${value}`;
        }

        /*
            节流就像英雄的技能CD
            举个例子:
                剑圣的R技能冷却CD中不能发技能,冷却CD结束后,想在哪个时间点放技能都可以
            节流的思想也是如此 开始的时候会执行fun一次,第二次执行fun与第一次fun执行的时间间隔必须不小于delay
         */
        function throttle(fun, delay) {
            //last:上一次执行fun函数的时间戳
            let last, deferTimer
            return function (args) {
                //now获取当前时间戳
                let now = +new Date();
                if (last && now - last < delay) {
                    clearTimeout(deferTimer);
                    deferTimer = setTimeout(function () {
                        last = +new Date();
                        fun.call(this, args);
                    }, last - now + delay)
                    /*
                        为什么是last-now+delay而不是delay?
                            如果为delay时,当你点击触发throttle函数时,必须要等待delay才会执行,然而你点击触发throttle函数的那个时间点和上一次执行fun函数的时间点应该就忽略了,而节流是第二次执行fun与第一次执行fun的时间间隔必须不小于delay,不是你点击触发throttle函数的那个时间点和下一次执行fun的时间间隔不小于delay,
                            所以应该是last-now+delay而不是delay
                     */
                } else {
                    last = now;
                    fun.call(this, args);
                }
            }
        }

        const outputRes = throttle(changeOutputVal, 2000);
        const inputEle = document.querySelector("#name");
        inputEle.addEventListener("input", (eve) => {
            outputRes(eve.target.value);
        });
    }

</script>
</html>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值