Debounce function that fires FIRST then debounces subsequent actions

别说谁变了你拦得住时间么 提交于 2020-05-27 03:01:11

问题


Every example of a debounce function that I've seen so far prevents an action from happening multiple times for a specified time span, and then executes the action one time when the specified time span has elapsed, then resets the timer. For example, the $mdUtil.debounce function that is included in Angular Material.

What I'm looking for is a debounce function that executes the action immediately and then prevents subsequent multiple actions from firing until the timer resets. This has the benefit of the user not having to wait until the debounce time has elapsed until their action is taken while still achieving the goal of debouncing the actions.

Has anyone seen one or had luck creating one?

Update After some more thought, the debounce function should fire the action immediately and then, if the debounced function was called again within the debounce time span, it should fire the action a second time before resetting the timer in case the second call changed any values.


回答1:


edit: adding jsbin implementation

Lodash's debounce can do both. You'll have to specify whether it's leading or trailing.

https://lodash.com/docs#debounce

_.debounce(sendMail, 300, {
  'leading': true,
  'trailing': false
})

you can also write your own debounced function in just few lines jsbin example:

This will click first then debounce subsequent clicks.

function debounce(func, delay) {
  console.log('debounce called with delay', delay);
  var timer = 0;
  return function debouncedFn() {
    if (Date.now() - timer > delay) {
      func();
    }
    timer = Date.now();
  };
}


来源:https://stackoverflow.com/questions/34552038/debounce-function-that-fires-first-then-debounces-subsequent-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!