[OHIF-Viewers]医疗数字阅片-医学影像-Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库。_.throttle(func, [wait=0], [options={}])实例解析防抖动(Debouncing)和节流阀(Throttling)
[OHIF-Viewers]医疗数字阅片-医学影像-Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库。_.throttle(func, [wait=0], [options={}])实例解析防抖动(Debouncing)和节流阀(Throttling)
OHIF-Viewers里面有一句
import throttle from 'lodash.throttle';
先找手册,这里贴中文的手册地址吧,看着方便一点
https://www.lodashjs.com/docs/lodash.throttle
npmjs下载地址
https://www.npmjs.com/package/lodash.throttle
npm i lodash.throttle
_.throttle(func, [wait=0], [options={}])
创建一个节流函数,在 wait 秒内最多执行 func
一次的函数。 该函数提供一个 cancel
方法取消延迟的函数调用以及 flush
方法立即调用。 可以提供一个 options 对象决定如何调用 func
方法, options.leading 与|或 options.trailing 决定 wait 前后如何触发。 func
会传入最后一次传入的参数给这个函数。 随后调用的函数返回是最后一次 func
调用的结果。
注意: 如果 leading
和 trailing
都设定为 true
则 func
允许 trailing 方式调用的条件为: 在 wait
期间多次调用。
如果 wait
为 0
并且 leading
为 false
, func
调用将被推迟到下一个点,类似setTimeout
为0
的超时。
参数
func
(Function): 要节流的函数。[wait=0]
(number): 需要节流的毫秒。[options={}]
(Object): 选项对象。[options.leading=true]
(boolean): 指定调用在节流开始前。[options.trailing=true]
(boolean): 指定调用在节流结束后。
返回
(Function): 返回节流的函数。
例子
// 避免在滚动时过分的更新定位 jQuery(window).on('scroll', _.throttle(updatePosition, 100)); // 点击后就调用 `renewToken`,但5分钟内超过1次。 var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); jQuery(element).on('click', throttled); // 取消一个 trailing 的节流调用。 jQuery(window).on('popstate', throttled.cancel);
实例解析防抖动(Debouncing)和节流阀(Throttling)
原文:Debouncing and Throttling Explained Through Examples
防抖(Debounce)和节流(throttle)都是用来控制某个函数在一定时间内执行多少次的技巧,两者相似而又不同。
当我们给 DOM 绑定事件的时候,加了防抖和节流的函数变得特别有用。为什么呢?因为我们在事件和函数执行之间加了一个控制层。记住,我们是无法控制 DOM 事件触发频率的。
看下滚动事件的例子:
假想一下,你在电梯中,门快要关了,突然有人准备上来。电梯并没有改变楼层,而是再次打开梯门。电梯延迟了改变楼层的功能,但是优化了资源。
在顶部按钮上点击或移动鼠标试一下: