如何防止表单按钮被快速点击很多次

How can I prevent a form button being clicked lots of times very fast

如何防止表单按钮被快速点击很多次?

我正在使用 html5 和 angular2。

目前他们只需点击即可加载。

我需要尽可能只允许一次,或者至少他们必须等待 2 秒才能再次点击。

您可以尝试类似的方法:

@Component({
  (...)
  template: `
    <div (click)="handleClick()">Click</div>
  `
})
export class MyComponent {
  constructor() {
    this.clicked = false;
  }

  handleClick() {
    if (!this.clicked) {
      this.clicked = true;
      setTimeout(() => {
        this.clicked = false;
      }, 2000);
    }
  }
}

我认为您还可以利用 Rx(这取决于用例)和 debounceTime 运算符:

Emits an item from the source Observable after a particular timespan has passed without the Observable omitting any other items.

当点击时间非常快时,这允许在一定时间(此处为 500 毫秒)后仅触发最后一个事件:

this.ctrl.valueChanges.debounceTime(500).mergeMap(
  val => {
    return this.http.get('https://api.github.com/users?d='+val);
  }).subscribe(
    data => {
      console.log(data);
    }
  );

此示例显示了用户填写输入时的此类行为。

您可以将此与 setTimeout 混合使用,以再次启用处理一段时间。

Rob Wormald 就此类问题提出了建议。有关详细信息,请参阅此 link:

按钮的作用是什么?是表单提交还是刷新页面按钮!最好的解决方案是在用户单击该按钮后立即将其禁用,以防您不导航到其他页面。

参考这个

希望对您有所帮助。

它不是特定于 angular2,但我用它来消除函数调用:

function debounce(delay, fn, fnArgsArray){
    if(typeof fn.debouncing === 'undefined' || fn.debouncing == false){
        fn.debouncing = true;
        setTimeout(() => fn.debouncing = false, delay);
        fn.apply(this, fnArgsArray);
    }
}

示例:

<button onclick="debounce(2000, add, [2, 4]);">testen</button>

function add(a, b){
    var sum = a + b;
    console.log(a + " + "+ b + " = " + sum);
}