单击图标 2 秒后如何停止动画?

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

我正在尝试通过点击一个图标来启动动画,然后它应该只动画 2 秒然后它应该自动停止 我使用了一个变量“spin”,它被初始化为 false,点击它传递给 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 文件:

        public spin=false;

       refreshTaskList() {
            this.spin=true;
       }

因此,如果我将其保留为 [spin]="trueé",它将永远旋转,就像我现在所做的那样,单击时它将开始旋转并且永不停止!!我希望它开始旋转并在 2 秒后停止

使用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);
    }

我认为最简单的解决方法是使用 setTimeout。但请确保通过调用 clearTimeout() 来清除超时,当多次按下按钮时,它会在最后一次单击按钮后 2 秒完成。

public spin = true;
private timeout = null;

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