lodash
常用API
函数 | 说明 | 语法 |
---|---|---|
debounce | 防抖函数 | debounce(func, [wait=0], [options=]) |
Throttle | 节流函数 | |
debounce
debounce
函数确保在函数最后一次触发后,等待指定的时间间隔后再执行。- 当函数被频繁触发时,
debounce
会在最后一次触发后开始计时,在指定时间间隔后执行一次函数。 debounce
适用于需要等待一段时间后执行的函数,例如搜索框输入后等待用户停止输入一段时间后再触发搜索操作。
语法:
debounce(func, [wait=0], [options=])
参数:
func
(Function): 要防抖动的函数。[wait=0]
(number): 需要延迟的毫秒数。[options=]
(Object): 选项对象。[options.leading=false]
(boolean): 指定在延迟开始前调用。[options.maxWait]
(number): 设置func
允许被延迟的最大值。[options.trailing=true]
(boolean): 指定在延迟结束后调用。
基础使用:
import {debounce} from 'loadsh'
Throttle
throttle
函数确保在指定的时间间隔内,函数最多执行一次。- 当函数被频繁触发时,
throttle
会在每个时间间隔内仅执行一次函数,并忽略其他触发,直到时间间隔结束。 throttle
适用于需要稳定的、间隔性的执行函数,例如防止按钮多次点击触发同一操作,或者在滚动事件中控制函数的执行频率。