Title

一、节流

一段时间内只能触发一次,如果这段时间内触发多次事件,只有第一次生效会触发回调函数,一段时间过后才能再次触发(一定时间内只执行第一次)

应用场景

1、鼠标连续不断地触发某事件(如点击),只在单位时间内只触发一次;

2、懒加载时要监听计算滚动条的位置,但不必每次滑动都触发,可以降低计算的频率,而不必去浪费 CPU 资源;

function debounce(fn,delay){
  let timer null;
  return function(){
    if(timer){
      clearTimeout(timer)
    }
    timer = setTimeout(fn,delay)
  }
}

二、防抖

在事件被触发时,延迟n秒后再触发回调函数,如果n秒内又触发了事件,则会重新开始计算时间(一定时间内最后一次生效)

应用场景

用户在输入框中连续输入一串字符时,可以通过防抖策略,只在输入完后,才执行查询的请求,这样可以有效减

少请求次数,节约请求资源

function debounce(fn,delay){
  let timer null;
  return function(){
    if(timer){
      clearTimeout(timer)
    }
    timer = setTimeout(fn,delay)
  }
}

 

 

posted on 2023-01-20 01:55  chccee  阅读(12)  评论(0编辑  收藏  举报