手写防抖和节流函数


/* 
防抖:是指在事件被触发后,在n秒内函数只执行一次,如果在n秒内重复被触发,则重新开始计时
*/

/**
 * 防抖函数,计时结束时触发
 * @param { Function } callBack
 * @param { Number } 延迟秒数
 * @returns { Function } 
*/ 
function debounce1 (funs, delay) {
    let timer
    return function () {
        let arg = arguments
        if(timer) { clearTimeout(timer) }
        timer = setTimeout(() => {
            funs(...arg)
        }, delay)
    }
}

/**
 * 防抖函数,立即执行防抖函数:先执行在计时
 */
function debounce2 (funs, delay) {
    let timer
    return function () {
        // 接收参数
        let arg = arguments
        // 如果timer为true,说明计时还没结束,则取消上次计时,重新开始计时
        if (timer) { clearTimeout(timer)}
        // 通过timer的值来确定是否执行回调函数
        let callNow = !timer
        // 利用定时器计时,delay秒内无操作则令timer为null,下次操作立即执行回调
        timer = setTimeout(() => {
            timer = null
        }, delay)
        if (callNow) {
            funs(...arg)
        }
    }
}

/* 
节流:是指连续触发事件但是在n秒内只执行一次
*/
/**
 * 节流函数
 */
function throttle (funs, wait) {
    let timer 
    return function () {
        let arg = arguments
        if (timer) return
        timer = setTimeout(() => {
            timer = null
            funs(...arg)
        }, wait);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值