防抖和节流

防抖和节流是针对响应跟不上触发频率这类问题的两种解决方法防抖是给定一个周期延迟执行动作,若期间又被触发,则重新设定周期,直到周期结束,执行动作。

 <style>
        #content {
            width: 150px;
            line-height: 150px;
            text-align: center;
            color: #fff;
            background-color: #ccc;
            font-size: 80px;
        }
    </style>
</head>

<body>
    <div id="content">1</div>
</body>
<script>
    let num = 1;
    let content = document.getElementById('content');
    //计数函数
    function count() {
        content.innerHTML = num++;
    };
    function debounce(func, wait) {
        let timer;
        return function() {
          let context = this; // 注意 this 指向
          let args = arguments; // arguments中存着e
             
          if (timer) clearTimeout(timer);
     
          timer = setTimeout(() => {
            func.apply(this, args)
          }, wait)
        }
    }
    content.onmousemove = debounce(count, 1000);

节流的策略是,固定周期内,只执行一次动作,若在此周期内有新事件触发,不执行。周期结束后,又有事件触发,开始新的周期。 

<style>
        #content {
            width: 150px;
            line-height: 150px;
            text-align: center;
            color: #fff;
            background-color: #ccc;
            font-size: 80px;
        }
    </style>
</head>

<body>
    <div id="content">1</div>
</body>

<script>
    let num = 1;
    let content = document.getElementById('content');
    //计数函数
    function count() {
        content.innerHTML = num++;
    };
    // 定时器版
    function throttle(fun, wait) {
        let timeout;
        return function () {
            let context = this;
            let args = arguments;
            if (!timeout) {
                timeout = setTimeout(() => {
                    timeout = null;
                    fun.apply(context, args)
                }, wait)
            }
        }
    }
    //给content绑定鼠标移动事件
    content.onmousemove = throttle(count, 3000);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值