• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
社会优先于个人
博客园    首页    新随笔    联系   管理    订阅  订阅
节流throttle和防抖debounce

节流throttle

当频繁触发一个函数的时候,在规定时间内,只有第一次生效。

比如,滚动事件,请求数据。

<body>
     <div id="hehe" style="height: 10000px;">hehe</div> 
</body>
<script>
function throttle(fun,delay){
  let lasttime=0;
  return function (params) {
    let nowtime=Date.now();
    if(nowtime-lasttime>delay){
      fun();
      lasttime=nowtime;
    }
  }
}

function fun(){
  console.log('throttle')
}

document.onscroll=throttle(fun,2000)

</script>

防抖debounce

当频繁触发一个函数的时候。如果触发一个函数,在规定的时间内,又再次触发,那就取消第一次的,重新开始计时,如果规定时间内,又有触发,再次取消上一次的,重新计时,只有最后一次生效。

比如,根据关键词搜素,在input框输入关键字,在规定的时间内,最后一次才触发函数请求数据。

<body>
    <div id="search">search</div> 
    <input type="text" id="textcontent"> 
</body>
<script>
function debounce(fun,delay){
  let timer=null;
  
  return function (params) {
    clearTimeout(timer);
    timer=setTimeout(() => {
      fun();
    }, delay); 
  }
}

function fun(){
  console.log('http request')
}

document.getElementById('search').onclick=debounce(fun,2000)

</script>
posted on 2022-02-23 14:15  社会优先于个人  阅读(34)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3