使用定时器和闭包原理实现简单的节流函数
参数fn参数为需要进行节流的函数,参数timer为定义的节流时间
// 回调函数的类型
type ReFn = (...args:any) => void
// 节流函数的类型
type ThFn = (fn: ReFn, timer: number) => ReFn
const throttle: ThFn = (fn, timer) => {
let time: any = null
const _throttle = (...args:any) => {
if (time) clearTimeout(time)
time = setTimeout(() => {
fn.apply(this,args)
}, timer);
}
return _throttle
}
export default throttle
以下为调用代码
const handler = throttle((a,b) => { console.log(a,b) }, 500)
const getLog = () => {
handler('参数1','参数2')
}