/** * 节流函数 * @param {*} fun 需要节流的函数 * @param {*} time 节流时间间隔 * @param {*} first 节流函数在节流时间间隔内是执行第一个还是最后一个 */ functionthrottle(fun, time = 10, first = true){ if (first){ let flag = false returnfunction(){ if (flag) return flag = true
let that = this let args = arguments fun.apply(that, args)
setTimeout(_ => { flag = false }, time) } } else { let flag = false let that = null let args = null returnfunction(){ if (flag) { that = this args = arguments return } flag = true
/** * 函数防抖封装函数 * @param {*} fun 需要防抖的函数 * @param {*} time 防抖时间间隔 * @param {*} first 函数在一次的防抖时间内是执行第一个还是最后一个 */ functiondebounce(fun, time = 10, first = true){ if (first){ let flag = false let handle = null
returnfunction(){ if (handle) clearTimeout(handle) handle = setTimeout(_ => { flag = false }, time)
if (flag) return flag = true
let that = this let args = arguments fun.apply(that, args) } } else { let flag = false let handle = null returnfunction(){ if (handle) clearTimeout(handle)
let that = this let args = arguments handle = setTimeout(_ => { flag = false fun.apply(that, args) }, time)