防抖与节流

防抖

比如在百度搜索时,input事件并不会一直触发,会在你停止输入后2s左右触发。这就叫事件防抖

下面是简单小实例

<!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>
    <input type="text" />
</body>
</html>
<script>
  
  function antishake(fn,wait){
    let timeOut=null
    return function(){
        if(timeOut){
            clearTimeout(timeOut)
        }
        timeOut=setTimeout(fn,wait)
    }
  }
  let telInput=document.querySelector('input')
  telInput.addEventListener('input',antishake(demo,200))

  function demo(){
    console.log('发起请求')
  }
</script>

节流

使用场景:例如在提交表单时网络卡顿,某些手残党不停的疯狂点击提交按钮,会导致每点击一次就发一次请求,这样就会发无数次请求。那么就要让几秒之内只提交一次。这就是节流

下面是用鼠标滑动举例,在鼠标滑动时,每两秒发一次请求。

<!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>
<style>
    .box{
        width: 300px;
        height: 300px;
        background-color: aqua;
    }
</style>
<body>
    <div class="box"></div>
</body>
</html>
<script>
  let box =document.querySelector('.box')
  box.addEventListener('mousemove',throttle(demo,2000))
  //封装节流
  function throttle(event,time){
    let timer=null
    return function(){
        if(!timer){
            timer=setTimeout(()=>{
                event()
                timer=null
            },time)
        }
    }
  }
  function demo(){
    console.log('发起请求')
  }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值