触发 FIRST 然后去抖动后续动作的去抖动函数 [英] Debounce function that fires FIRST then debounces subsequent actions

查看:26
本文介绍了触发 FIRST 然后去抖动后续动作的去抖动函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我所看到的每个去抖动函数示例都会防止某个动作在指定的时间跨度内多次发生,然后在指定的时间跨度过去后执行该动作一次,然后重置计时器.例如,Angular Material 中包含的 $mdUtil.debounce 函数.

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.

推荐答案

edit: 添加 jsbin 实现

edit: adding jsbin implementation

Lodash 的 debounce 可以做到这两点.您必须指定它是前导还是尾随.

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
})

您还可以在短短几行中编写自己的去抖动函数jsbin 示例:

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();
  };
}

这篇关于触发 FIRST 然后去抖动后续动作的去抖动函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆