JS 防抖、节流

<!document>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style></style>
</head>
<body>
    <button id="save">提交/保存</button>
    <input type="text" placeholder="请输入" id="search"/>
</body>
<script>
    // 防抖 概述:当持续触发事件时,保证只执行最后一次事件的处理函数
    // 应用场景:onchang oninput 搜索功能等
    function debounce(fn){
        let timer = null;
        return function () {
            // 如果定时器存在,就清除掉
            if (timer) {
                clearTimeout(timer);
            }
            console.log('debounce==', this)
            // 否则就创建新的定时器

            // .bind(this)将timer的this改变成当前事件的this
            timer = setTimeout(function(){
                // 需要执行的方法
                console.log('debounce setTimeout==', this)
                // 将fn的this改变成input的this
                fn.call(this);
            }.bind(this), 500)
        }    
    }


    // 节流 概述:当持续触发事件时,保证一段时间内执行一次事件处理函数
    // 应用场景:加载更多  屏幕滚动 高频点击提交按钮等
    function throttle(fn){
        let flag = true;
        if (!flag) {
            return;
        }
        flag = false;
        return function(){
            setTimeout(function(){
                fn();
                flag = true;
            }, 500)
        }
    }  

  document.getElementById('search').addEventListener('input', debounce(function(){
        console.log('debounce callback==', this)
        console.log(this.value)
    }))
    
    document.getElementById('save').addEventListener('click', throttle(function(){
        console.log('throttle callback==', this)
    }))    
</script>
</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值