前端手写题: 节流和防抖

节流

1.不传参的写法

<button type="button" class="throttleBtn">节流</button>
	function throttle(fn,delay){
      let timeOut = null
      return function(){
        if(!timeOut){
          timeOut = setTimeout(()=>{
            fn()
            timeOut = null
          },delay)
        }
      }
    }
	function notice(value){
      console.log('节流执行!',value)
    }
    $('.throttleBtn').click(throttle(notice,1000))

2.传参的写法

function throttle(fn,delay,args){
      let timeOut = null
      return function(){
        if(!timeOut){
          timeOut = setTimeout(()=>{
            fn.apply(this, args)
            timeOut = null
          },delay)
        }
      }
    }
    function notice1(value,value1){
      console.log('节流执行!',value,value1)
      $('.content').append('节流执行!'+value+','+value1)
    }
    $('.throttleBtn').click(throttle(notice1,1000,[55,33]))

请添加图片描述

防抖

1.不传参的写法

<button type="button" class="debounceBtn">防抖</button>
	function debounce(fn,delay){
      let timeOut = null
      return function(){
        if(timeOut) clearTimeout(timeOut)
        timeOut = setTimeout(fn,delay)
      }
    }
    function notice(){
      console.log('防抖执行!')
    }
    $('.debounceBtn').click(debounce(notice,1000))

2.传参的写法

    function debounce(fn,delay,args){
      let timeOut = null
      return function(){
        if(timeOut) clearTimeout(timeOut)
        console.log('fn',fn,timeOut)
        timeOut = setTimeout(()=>{
          fn.apply(this, args)
        },delay)
      }
    }
    function notice(value){
      console.log('防抖执行!',value)
    }
    // 把参数放在后面,如果是apply 则传数组;如果是call 则传arguments;
    $('.debounceBtn').click(debounce(notice,1000,[888]))

请添加图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值