2017-12-28 40 views
0

このサンプルプログラムでは、ボタンをクリックしてScore変数を画面に連続して印刷すると、タイマーが1000msで開始されます。スコアが100になったら、タイマーを500msで実行します。スコアが300になったら、タイマーを250msで実行します。タイマ変数を減らす

マイスタートのfuctionとTSファイル内の関数のスコアは以下の通りです:

public ScoreNumber: number = 0; 
public TimeOfScore; 
public Start() { 
    this.TimeOfScore= setInterval(() => { 
     this.Score(); 
    }, 1000); 

public Score(){ 
ScoreNumber++; 
} 

スタート機能は、HTMLファイル内のボタンで呼び出します。そのような画面上の楽譜の印刷:

<div>{{Score}}</div> 

私はそのようなコードを変更:

public ScoreNumber: number = 0; 
public TimeOfScore; 
public time:number=1000; 
public Start() { 
    this.TimeOfScore= setInterval(() => { 
     this.Score(); 
    }, time); 

public Score(){ 
ScoreNumber++; 
if(this.ScoreNumber>100&&this.ScoreNumber<300){ 
this.time=500; 
} 
else if(this.ScoerNumber>300){ 
this.time=250; 
}  
} 

を私が望んだとして当然のコードは動作しませんでした。 Start関数は1回だけ呼び出します。この時間変数をどのように減らすことができますか?

答えて

0

明確な間隔と再設定

if(this.ScoreNumber>100&&this.ScoreNumber<300){ 
this.time=500; 
this.restartInterval(); 
} 
else if(this.ScoerNumber>300){ 
this.time=250; 
this.restartInterval(); 
} 

再起動インターバル機能

restartInterval() 
{ 
    clearInterval(this.TimeOfScore); 
    this.TimeOfScore= setInterval(() => { 
     this.Score(); 
    }, this.time); 
} 
+0

これは間違いありません。ありがとう。 – osmnfrkn61

+0

実行するたびにクリアすると、間隔を使用することに意味はありません。 – JJJ

+0

間隔は、スコアが100,300 ectなどの特定の条件でクリアされるたびにクリアされません –

0

1)だけ再帰のsetTimeout 2)JavaScriptの規則に従うを使用!

private scoreNumber: number = 0; 
private duration: number = 1000; 
private running = false; 

public start(){ 
    if(this.running) return; 
    this.running = true; 
    run(); 
} 

private run(){ 
    this.scoreNumber++; 
    if(this.scoreNumber > 100 && this.scoreNumber < 300){ 
    this.duration = 500; 
    } else if(this.scoreNumber > 300){ 
    this.duration = 250; 
    } 
    setTimeout(run, this.duration); 
} 
関連する問題