函数防抖

什么是函数防抖?

简单来说,函数防抖指的是多次触发事件,事件处理函数只执行一次;

应用场景:

在连续点击查询按钮情况下或者缩放屏幕要触发某个事件等等;

实际应用:

下面来介绍两种实现方法:

  1. 点击按钮的最后触发时间
    (1)初始化timer为null
    (2)在初次点击查询按钮的时候, 给timer赋值(赋值函数中触发事件的调用)
    (3) 如果再次点击那会,timer已经有值, 那就先清除timer再重新给timer赋值
function debounceA(fn, delay) {
     let timer = null;
     return function() {
         clearTimeout(timer)
         timer = setTimeout(function() {
             fn.apply(this)
         }, delay)
     }
 }

  1. 点击按钮立马触发条件,不过同时点击的话自定义时间内只执行一次
function debounceB(fn, delay) {
  	   let timer = null;
       return function() {
           timer === null && fn.apply(this)
           timer != null && clearTimeout(timer)
       
           timer = setTimeout(function() {
               clearTimeout(timer);
               timer = null;
           }, delay)
       }
   }

demo:

<!DOCTYPE html>
<html lang="en">
<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>
</head>
<body>
    <button id='btn1'>最后执行</button>
    <button id='btn2'>立即执行</button>
    <script type="text/javascript">
    let btn1 = document.getElementById('btn1')
    let btn2 = document.getElementById('btn2')
    let count1 = 0;
    let count2 = 0;
    function debounceA(fn, delay) {
        let timer = null;
        return function() {
            clearTimeout(timer)
            timer = setTimeout(function() {
                fn.apply(this)
            }, delay)
        }
    }
    function debounceB(fn, delay) {
        let timer = null;
        return function() {
            timer === null && fn.apply(this)
            timer != null && clearTimeout(timer)
        
            timer = setTimeout(function() {
                clearTimeout(timer)
                timer = null
            }, delay)
        }
    }
    btn1.onclick = debounceA(function() {
        count1++;
        console.log(`最后执行${count1}次`)
    }, 500)

    btn2.onclick = debounceB(function() {
        count2++;
        console.log(`立即执行${count2}次`)
    }, 500)
    </script>
</body>
</html>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值