防抖以及底层实现js高级

<style>
        div{
            margin: 0 auto;
            width: 200px;
            height: 200px;
            background-color: orange;
            text-align: center;
            color: #000;
            font-size: 20px;
        }
    </style>
    <div class="box"></div>
    <script>
    
        const box =document.querySelector('.box')
        let i =1
        function mouseMove (){
            box.innerHTML =i++
        }
        box.addEventListener('mousemove',mouseMove)
</script>


  防抖:单位时间内,频繁触发事件,只执行最后一次
             

实现性能优化

场景:搜索框输入

  底层实现

  1.         声明定时器变量
  2.         在事件触发时,判断是否有定时器,如果有定时器,清除以前的定时器
  3.         如果没有定时器,则开启定时器,存入定时器变量里
  4.         在定时器里面写函数调用
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <style>
        div{
            margin: 0 auto;
            width: 200px;
            height: 200px;
            background-color: orange;
            text-align: center;
            color: #000;
            font-size: 20px;
        }
    </style>
    <div class="box"></div>
    <script>
        //防抖:单位时间内,频繁触发事件,只执行最后一次
        //实现性能优化
        //场景:搜索框输入
        const box =document.querySelector('.box')
        let i =1
        function mouseMove (){
            box.innerHTML =i++
        }
        // box.addEventListener('mousemove',mouseMove)
        //底层实现
     function  debounce(fn,t){
        //声明定时器变量
            let timer
            return function(){
        //在事件触发时,判断是否有定时器,如果有定时器,清除以前的定时器
                if(timer) clearTimeout(timer)
        //如果没有定时器,则开启定时器,存入定时器变量里面
               timer= setTimeout(function(){
        //在定时器里面写函数调用
            fn()
               },t)
            }
        
        }

        box.addEventListener('mousemove',debounce(mouseMove,500))

    </script>
</body>
</html>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值