手撕代码——防抖函数和节流函数

//防抖函数
function debounce(func,delay) {
    let timeoutId
    return function(...args) {
        //这里的this指向的是input这个对象
        let context =this
        clearTimeout(timeoutId)
        timeoutId = setTimeout(() => {
            func.apply(context,args)
        },delay)
    }
}

const debounceFn = debounce(function() {
    //这里执行要进行防抖的具体操作
},500)
Element.addEventerListener('input',debounceFn)


//节流函数
function throttle(func,delay) {
    let canRun = true
    return function(...args) {
        if(canRun) {
            const context = this
            canRun = false
            func.apply(context,args)

            setTimeout(() => {
                canRun = true
            },delay)
        }
    }
}

const = throttleFn = throttle(function() {
    //这里执行要进行节流的具体操作
},1000)
Element.addEventerListener('scroll',throttleFn)

        上面的代码中都绑定了this和arguments,下面将展示使用this和arguments的简单场景

//传递参数的场景
function debounce(fn, delay) {
  let timer = null;
  
  return function(...args) {
    const context = this;
    
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
}

function sayHello(name) {
  console.log(`Hello, ${name}!`);
}

const debouncedSayHello = debounce(sayHello, 500);

// 调用防抖函数,并传递参数
Element.addEventerListener('input',debounceFn('KangKang')
//需要使用this的场景
function debounce(fn, delay) {
  let timer = null;
  
  return function(...args) {
    const context = this;
    
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
}

function handleInput(input) {
  console.log(`Input value: ${input.value}`);
}

const inputElement = document.getElementById('myInput');

// 创建一个带防抖功能的事件处理函数
const debouncedHandleInput = debounce(handleInput, 500);

// 添加事件监听器
inputElement.addEventListener('input', function() {
  debouncedHandleInput(this); // 将input对象作为参数传递给防抖函数
});

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值