How to stop animation after clicking on an icon by 2 seconds?

Viewed 89

i'm trying to start an animation by clicking on an icon and then it should just be annimated for 2 seconds and then it should automatically stop i used a variable "spin" that it's initialized as false and on clicking on the icon it passes to true

<span class="mr-4 pr-3">
  <fa-icon [spin]="spin" style="color : white; font-size: large; top: 0; " [icon]="faArrowAltCircleDown"
    (click)="refreshTaskList()"></fa-icon>
</span>

.ts file:

        public spin=false;

       refreshTaskList() {
            this.spin=true;
       }

so if i leave it as [spin]="trueƩ" it will be spinning for ever and like i did it now it will start spinning when clicked and never stop !! i want it to start spinning and stop after 2 seconds

2 Answers

Use timeout

    refreshTaskList(){
//do nothing if spin already spining in case click few times in 2 seconds
    if(this.spin)
       return;
    this.spin=true;
    setTimeout(()=>{this.spin=false;},2000);
    }

I think easiest fix for this would be by using setTimeout. But make sure to clear timeouts by calling clearTimeout(), when pressing button multiple times, so it completes 2 second after latest button click.

public spin = true;
private timeout = null;

refreshTaskList() {
    if(this.timeout){
      clearTimeout(this.timeout);
    }
    this.spin = true;
    this.timeout = setTimeout(()=>{
      this.spin=false
    }, 2000);
}

Related