代码实现简单防抖与节流

本文介绍了JavaScript中的防抖(debounce)和节流(throttle)两种优化函数性能的技术,分别提供了非立即执行版、立即执行版以及双剑合璧版的防抖实现,以及时间戳版和定时器版的节流示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

防抖


1、非立即执行版

function debounce(fn,time=250,context){
           let timer=null
            return function(...args){
                const self=context||this
                if(timer){
                    clearTimeout(timer)// 每次执行的时候把前一个 setTimeout clear 掉
                }
                timer=setTimeout(()=>{
                    fn.apply(self,args)
                    timer=null
                },time)
            }
        }

2、立即执行版

// 防抖动函数-立即执行版
function debounce(func, delay) {
    let timer;
    return function () {
        let context = this;
 
        if (timer) clearTimeout(timer); // 每次执行的时候把前一个 setTimeout clear 掉
 
        let callNow = !timer;
        timer = setTimeout(() => {
            timer = null;
        }, delay)
 
        if (callNow) func.apply(context, arguments);
    }
}

3、双剑合璧版

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行,false 表非立即执行
 */
function debounce(func, delay, immediate) {
    // 双剑合璧版
    let timer;
    return function () {
        let context = this;
        
        if (timer) clearTimeout(timer);
        if (immediate) {
            let callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
            }, delay)
            if (callNow) func.apply(context, arguments);
        } else {
            timer = setTimeout(() => {
                func.apply(context, arguments);
            }, delay)
        }
    }
}

节流

1、时间戳版

  function throttle(fn, time = 250,context) {
          let lastTime = null;
          return function (...args) {
            const self=context||this
            const now = Date.now(); //当前时间
            if (!lasttime||now - lastTime >= time) {
              fn.apply(self,args);//帮助执行函数,改变上下文
              lastTime = now;
            }
          };
        }

2、定时器版

function throttle(func, wait) {
    // 定时器版
    let timer;
    return function () {
        let context = this;
        if (!timer) {
            timer = setTimeout(() => {
                timer = null;
                func.apply(context, arguments)
            }, wait)
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值