簡體   English   中英

Rxjs 取消訂閱后定時器重新啟動

[英]Rxjs timer restarts after unsubscribe

我開始制作一個簡單的游戲來測試反應。 當紅色矩形變為綠色時,玩家必須點擊圖形並顯示結果。 問題是單擊矩形后計時器再次啟動。我為此使用取消訂閱,但沒有結果。

示例: https://stackblitz.com/edit/angular-ivy-w8uejd?file=src%2Fapp%2Fapp.component.ts

代碼:

HTML

<div (click)="onRegtangleClicked()" class="rectangle" id="rectangle"></div>
<div class="button">
    <button (click)="onStartClicked()" class="btn btn-success">Start</button>
</div>
<p class="text">You score is:  {{time}} (lower is better)</p> 

SCSS

.rectangle {
    position: relative;
    height: 500px;
    width: 100%;
    background-color: rgb(255, 0, 0);
    cursor: pointer;
  }
.button{
    margin-left: 40%;
    margin-top: 2%;
    position: relative;
}
.text{
    font-size: large;
    position: relative;
    margin-left: 40%;
}

typescript

import { Component, OnInit } from '@angular/core';
import { timer } from 'rxjs';

@Component({
  selector: 'app-reflexgame',
  templateUrl: './reflexgame.component.html',
  styleUrls: ['./reflexgame.component.scss'],
})
export class ReflexgameComponent implements OnInit {
  time: number = 0;
  subscription: any;

  constructor() {}

  ngOnInit(): void {}

  onStartClicked() {
    let randomNumber:number = Math.random() * 5;
    setInterval(() => {
      document.getElementById('rectangle')!.style.backgroundColor = 'green';
      this.observableTimer();
    }, randomNumber * 1000);
  }
  onRegtangleClicked() {
    this.subscription.unsubscribe();
  }
  observableTimer() {
    this.subscription = timer(0, 1).subscribe((val) => {
      this.time = val;
    });
  }
}

我不知道我錯在哪里?

您的代碼中斷的原因是因為

  1. 您甚至在創建訂閱之前就調用unsubscribe() :要解決此問題,您可以添加一個標志以便知道訂閱是否處於活動狀態。
  2. 創建間隔時最好清除間隔。

兩種邏輯都對我有用,試一試

計時器一次又一次地重新啟動,因為在onStartClicked()方法中您使用的是setInterval 您在間隔內定義的邏輯每x秒連續執行一次,直到您調用clearInterval(theIntervalToClear)

在您的情況下,您應該使用setTimeout僅在x秒后觸發邏輯一次。

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM