【问题标题】:Lodash throttle - prevent function from being called an extra time after delayLodash 油门 - 防止函数在延迟后被额外调用
【发布时间】:2018-12-20 22:58:44
【问题描述】:

我想使用 lodash throttle 来使函数每 4 秒左右调用一次不超过一次。

如果用户尝试连续多次激活该功能,则只有第一次单击才能启动该功能。然而,该函数在延迟后 额外时间 被调用。它立即调用一次,延迟后再次调用。

如何防止额外调用?

thing = _.throttle(function() {
  console.log('function runs');
}, 4000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

<button onclick="thing()">click a few times</button>

(fiddle)

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:
    thing =  _.throttle( function() {
    
       $('#info').append('function runs' + '<br />') 
    
    }, 4000, {trailing:false});
    

    https://lodash.com/docs/#throttle

    【讨论】:

    • 这和debounce相同选项有什么区别?
    • 有人能解释一下为什么会这样吗?
    • @xr280xr TLDR;来自文档:“注意:如果前导和尾随选项为真,则仅当在等待超时期间多次调用节流函数时,才会在超时的后沿调用 func。”对我来说,一个很好的解释是“Debounce 技术允许我们将多个顺序调用“分组”在一个单一的调用中。 “throttle 和 debounce 的主要区别在于,throttle 保证函数定期执行,至少每 X 毫秒执行一次。” css-tricks.com/debouncing-throttling-explained-examples 帮助
    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 2021-11-06
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多