会先触发反跳功能,然后反跳后续动作 [英] Debounce function that fires FIRST then debounces subsequent actions

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

问题描述

到目前为止,我所看到的每个防抖动函数示例都可以防止操作在指定的时间段内多次发生,然后在指定的时间段过去后执行一次该操作,然后重置计时器.例如,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.

推荐答案

添加jsbin实现

Lodash的反跳可以同时做到.您必须指定它是前导还是尾随.

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

这篇关于会先触发反跳功能,然后反跳后续动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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