3

I would like to be able to execute foo() once regardless of whether I click on the button once or twice.

<span> (click)="foo()" </span>

foo() {
    console.log("You've clicked on foo");
}

I've tried using this stackoverflow answer but clicking on it twice still results in multiple console.logs. How would be able to only run this function once?

Note: Not really looking for triple/quadruple clicks (only single/double)

Jett
  • 781
  • 1
  • 14
  • 30

1 Answers1

1

Try to use setTimeout, clearTimeout and handle user clicks:

<span 
    (click)="func1()" 
    (dblclick)="func2()">
    Hello
</span>

TypeScript:

timer = 0;
delay = 200;
prevent = false;

func1(){
    this.timer = setTimeout(() => {
        if (!this.prevent) {
            this.sayHello();
        } 
        this.prevent = false;
    }, this.delay);
}

func2(){
    clearTimeout(this.timer);
    this.prevent = true;
    this.sayHello();
}

sayHello(){
    console.log('Hello, world!:)');
}

The work stackblitz example

StepUp
  • 36,391
  • 15
  • 88
  • 148