手写节流防抖函数

1、前言

日常积累,欢迎指正

2、节流函数

连续操作时操作间隔大于指定时间才会执行一次 - 常见应用:搜索框输入即查询

2.1、ES5 版本 - arguments

/** @desc 使用 arguments */
export function debounce(fn,delay=300){
    const timer=null
    return function(){
        if(timer){
            clearTimeout(timer)
        }
        timer=setTimeout(()=>{
            // fn.call(this,arguments)
            fn.apply(this,arguments)
        },delay)
    }
}

2.2、ES6 版本 - 剩余运算符

/** @desc 使用剩余运算符 */
export function debounce(fn,delay=300){
    const timer=null
    return function(...rest){
        if(timer){
            clearTimeout(timer)
        }
        timer=setTimeout(()=>{
            // fn.call(this,rest)
            fn.applay(this,rest)
            timer =null
        },delay)
    }
}

2.3使用

import debounce from 'debounce'
handleSearch = debounce(() => {
    // console.log('debounce');
    search();
}, 500)

handleSearch()

3、防抖函数

连续操作时操作指定时间执行一次 - 常见应用:可拖动元素的拖动

3.1、ES5 版本 - arguments

/** @desc 使用 arguments */
export function throttle(fn,time=300){
    const timer =null
    return function(){
        if(timer){
            return
        }
        timer=setTimeout(()=>{
            fn.apply(this,arguments)
            timer=null
        },time)
    }
}

3.2、ES6 版本 - 剩余运算符

/** @desc 使用剩余运算符 */
export function throttle(fn,time=300){
    const timer =null
    return function(...rest){
        if(timer){
            return
        }
        timer=setTimeout(()=>{
            fn.apply(this,rest)
            timer=null
        },time)
    }
}

3.3、使用

import throttle from 'throttle'
handleDrag = throttle(() => {
    // console.log('throttle');
    drag();
}, 500)

handleDrag()

在线效果预览

当前仅有防抖效果可预览-节流预览效果待添加

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值