节流与防抖函数理解

1.防抖函数:

debounce中文是“去弹跳”,它的概念是从机械开关和继电器中的去弹跳衍生出来的,就是将多个信号合并成一个信号。当事件被多次触发时,只执行最后一次。

function debounce(func, delay) {
    var timeout;
    return function(e) {
        console.log("清除",timeout,e.target.value)
        clearTimeout(timeout);
        var context = this, args = arguments
        console.log("新的",timeout, e.target.value)
        timeout = setTimeout(function(){
          console.log("----")
          func.apply(context, args);
        },delay)
    };
};

应用场景:输入框搜索 提交按钮点击事件

2.节流函数

throttle中文意思是节流阀,字面意思是它是让水流的速度整体放慢,不是让它不能流动。它的作用是让函数在某个时间段只执行一次。

function throttle(fn, threshhold) {
 var timeout
 var start = new Date;
 var threshhold = threshhold || 160
 return function () {

 var context = this, args = arguments, curr = new Date() - 0
 
 clearTimeout(timeout)//总是干掉事件回调
 if(curr - start >= threshhold){ 
     console.log("now", curr, curr - start)//注意这里相减的结果,都差不多是160左右
     fn.apply(context, args) //只执行一部分方法,这些方法是在某个时间段内执行一次
     start = curr
 }else{
 //让方法在脱离事件后也能执行一次
     timeout = setTimeout(function(){
        fn.apply(context, args) 
     }, threshhold);
    }
  }
}

节流函数适用于更加频繁的触发的情况,比如resize、touchmove、mousemove、scroll等频繁触发的事件,它会强制函数以固定的频率进行,适用于动画场景。
模拟场景:http://demo.nimius.net/debounce_throttle/

在节流函数中,异步函数的作用是延迟时间,并让方法在脱离事件之后执行最后一次。

3.调用方法

const a = throttle(() => { console.log(123) }, 3500)
a()
a()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值