全手打原创,转载请标明出处:
先重点说一下可能遇到的坑:主要在两个方法的选择上以及原本默认参数的设置,看完这篇总结你就知道怎么回事了~
throttle API走起
_.throttle(func, [wait=0], [options={}])
func (Function): 要节流的函数。
[wait=0] (number): 需要节流的毫秒数。
[options={}] (Object): 选项对象。
[options.leading=true] (boolean): 指定调用在节流开始前,默认true。
[options.trailing=true] (boolean): 指定调用在节流结束后,默认true。
throttle Demo走起(Vue写法)
testThrottle: _.throttle(function() { console.log("throttle"); }, 2000, { leading: true, trailing: false })
预先设定一个执行周期,当调用动作的时刻大于等于执行周期则执行该动作,然后进入下一个新的时间周期。
简言之:结束时间点不会随点击改变
_.debounce(func, [wait=0], [options={}])
func (Function): 要防抖动的函数。
[wait=0] (number): 需要延迟的毫秒数。
[options={}] (Object): 选项对象。
[options.leading=false] (boolean): 指定在延迟开始前调用,默认false。
[options.maxWait] (number): 设置 func 允许被延迟的最大值。
[options.trailing=true] (boolean): 指定在延迟结束后调用,默认true。
当调用动作触发一段时间后,才会执行该动作,若在这段时间间隔内又调用此动作则将重新计算时间间隔。
简言之:结束时间点会随点击改变