Angular可以启动按钮无法停止间隔

发布于 2025-01-21 09:12:12 字数 635 浏览 1 评论 0原文

我使用的是Angular,并且有此代码:

App.component.ts

started: boolean = false;

…

startStop() {
    if (!this.started) {
      setInterval(()=> { this.test() }, 1000); // not started so start the interval   
      this.started = true;
    } else if (this.started) {
      this.started = false;  // Its started so stop it');
      clearInterval();
    }
  }


test() {
  // do stuff only via interval if started
}

,然后我有一个按钮将其打开和关闭

App.component.html,

<button (click)=“startStop()”>Start / Stop</button>

即使“启动”更改为false,则间隔开启,但没有接触事件。

如何解决此问题?

I am using Angular and I have this code:

App.component.ts

started: boolean = false;

…

startStop() {
    if (!this.started) {
      setInterval(()=> { this.test() }, 1000); // not started so start the interval   
      this.started = true;
    } else if (this.started) {
      this.started = false;  // Its started so stop it');
      clearInterval();
    }
  }


test() {
  // do stuff only via interval if started
}

Then I have a button that turns it on and off

app.component.html

<button (click)=“startStop()”>Start / Stop</button>

The interval turns on but not off eventhough the variable "started" is changed to false.

How can I fix this issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三人与歌 2025-01-28 09:12:12

这不是clear Interval的工作方式。如果您有几个间隔怎么办?它会停止哪一个?

setInterval返回您应该将其传递给clear Interval的ID

startStop() {
    let intervalId
    if (!this.started) {
      intervalId = setInterval(()=> { this.test() }, 1000); // not started so start the interval   
      this.started = true;
    } else if (this.started) {
      this.started = false;  // Its started so stop it');
      clearInterval(intervalId);
    }
  }

This is not how clearInterval works. What if you have several intervals ? Which one will it stop ?

setInterval returns an id that you should pass to clearInterval

startStop() {
    let intervalId
    if (!this.started) {
      intervalId = setInterval(()=> { this.test() }, 1000); // not started so start the interval   
      this.started = true;
    } else if (this.started) {
      this.started = false;  // Its started so stop it');
      clearInterval(intervalId);
    }
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文