debounce & throttle 去疑

本文介绍了debounce(防抖)和throttle(节流)的概念及其应用场景。debounce确保在一段时间无操作后才执行函数,常用于窗口缩放、输入事件等;throttle则限制操作按一定频率执行,适用于滚动加载、点击事件等。提供了在线demo以直观感受两者差异,并引用了Underscore/Lodash中对这两个函数的详细描述。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

debounce 防抖,限定操作在一段时间、行为不活动之后发生;延迟执行,如窗口缩放行为、按键输入行为、点击行为,延迟回调;

throttle 节流,只是‘掐住’,限定操作按时间频率周期发生;将高频转为低频,间歇性执行,如滚动加载、点击,阻止回调被触发的太快;

上面两句话,可以完全解惑。

这里有一个在线 debounce & throttle demo,可以点击或移动鼠标感受一下两者之间的区别。

下面是 Underscore/Lodash 中的相关详细描述:

debounce

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.

创建一个debounce函数,该函数会延迟/延迟/延迟调用func对象,等待一段时间直到上次debounce函数调用执行完。debounce函数带有一个cancel方法来取消延迟的func对象调用和一个flush方法来立即调用它们。提供选项(options)以指示是否应在延迟事件之前(leading)和/或之后(trailing)调用func。func调用时会传入最后一次提供给 debounce函数的参数。 后续调用的debounce函数返回是最后一次func对象调用的结果。

函数最后一次调用之后等待一段时间,再次执行函数;

即控制用户操作停止到达一段时间之后再次执行。

……基于行为的不活动,去抖

resize, keyup, click,


throttle

Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the throttled function. Subsequent calls to the throttled function return the result of the last func invocation.

创建一个throttle函数,每一段时间内最多只会调用一次 func。被throttled(扼杀)的函数带有一个cancel方法来取消延迟的func调用和一个flush方法来立即调用它们。提供选项(options)以指示是否应在间隔事件之前(leading)和/或之后(trailing)调用func。func对象调用作为最后一次传参提供给throttle函数。调用throttle函数会返回最后一次func调用的结果。

当重复调用函数的时候,至少每隔一段时间,到达时间间隔后再调用一次该函数;控制程序触发频率较高的事件。

……基于时间的频率,节流

scroll, click


[options.leading=true] (boolean): 指定在延迟/节流开始前调用。
[options.trailing=true] (boolean): 指定在延迟/节流结束后调用。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值