0
私はエクササイズタイマーを作っています。私はReactを使っていますが、私はそれが私の特定の質問にとって重要だとは思わない。JavaScriptでタイムアウトのif文を入れ子にするよりも読みやすいアプローチですか?
タイマーは毎秒カウントダウンします。複数のセットがあり(各セットは異なる練習です)、すべてのセットがラウンドごとに繰り返されます。
以下のコードは動作しますが、読みにくくなり始めます。私はまた、各セットの後に休憩時間を追加する必要があるので、私が現在の方法を続けていくと、さらに多くのif文が必要になります。
timer() {
this.myTimer = setInterval(() => {
// When the set time goes down to 0...
if (this.state.setTimeRemaining === 0) {
// Increment the set number
this.setState({currentSet: this.state.currentSet + 1});
// Reset the remaining time
this.setState({setTimeRemaining: this.state.setLength + 1});
}
// When the last set in the round is passed...
if (this.state.currentSet > this.state.noOfSets) {
// Reset the set number
this.setState({currentSet: 1});
// Increment the round number
this.setState({currentRound: this.state.currentRound + 1});
}
// If we've finished...
if (this.state.currentRound > this.state.noOfRounds) {
this.updateProgress('complete');
}
// Minus 1 second from the current set time
this.setState({setTimeRemaining: this.state.setTimeRemaining - 1});
if (this.state.progress === 'running') {
// Update the timer bar's status
this.updateTimerBar();
}
}, 1000);
}
この状況にはどのような方法が最適ですか?私はswitch文を使うことができますか?私はBabelを使用していますので、最新のJavaScriptメソッド/構文を使用できます。
よく、1つは 'this.setState()'の中に複数の状態を設定できることです。それらをすべて分離する必要はありません –