【问题标题】:How to add setimeout on html如何在html中添加settimeout
【发布时间】:2019-03-29 06:21:51
【问题描述】:

我需要在 tr 悬停 3 秒后调用 mouseHoverTableRow() 函数。 如果悬停时间小于 3 秒,我不想调用 mouseHoverTableRow()。我在 mouseHoverTableRow() 上调用 API 该怎么做?

<tr *ngFor="let item of list" (mouseover)= "window.setTimeout('mouseHoverTableRow(item.id)', 3000)">
<td></td>
</tr

【问题讨论】:

标签: html angular


【解决方案1】:

直接在 html 中使用setTimeout 不是一个好习惯,因此您可以在您的内部编写相同的逻辑而不是执行上述操作

打字稿文件

 onMouseHover(id) {
    setTimeout ((id) => {
         this.mouseHoverTableRow(id)
      }, 3000);
  }

  mouseHoverTableRow(id:number){
  // your function body
  }

然后

在html中

<tr *ngFor="let item of list" (mouseover)= "onMouseHover(item?.id)">
<td></td>
</tr>

【讨论】:

  • 当用户悬停在tr 上时,上面的代码 sn-p 在 3 秒后执行,这不是问题。问题是当用户在tr 上悬停 3 秒时,应该执行代码。谢谢
【解决方案2】:

.ts

let timer;  // global timer

 onMouseHover(id) {

    this.clearTimer(); // clear your existing timer

    this.timer = setTimeout ((id) => { // set timer
         this.mouseHoverTableRow(id)
      }, 3000);
  }

 clearTimer(){
    // clear your timer
    if(this.timer)
       clearTimeout(this.timer)
 }

  mouseHoverTableRow(id:number){
  // your function body
  }

.html

<tr *ngFor="let item of list" (mouseover)= "onMouseHover(item?.id)" (mouseout)="clearTimer()">
<td></td>
</tr>

【讨论】:

  • 如果我悬停在 3000 以下,它仍然在调用。
  • @Mini 看看demo
猜你喜欢
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 2020-07-09
相关资源
最近更新 更多