Here is my program. I created the stopwatch with a start and stop button and everything worked as it should. My next step was to make the stopwatch react to the keyboard, via the spacebar. When I hit the start button, the stopwatch starts running. When I hit the spacebar, instead of the stopwatch just stopping at its current place, it restarts at 0 and begins to count up really quickly. The stop button works as it should.
import React from 'react';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {milliSecondsElapsed: 0};
this.handleStopClick = this.handleStopClick.bind(this);
this.keyPress = this.keyPress.bind(this);
}
keyPress = (e) => {
if (e.keyCode == 32){
handleStopClick();
}
}
getMilliseconds() {
return ("0" + this.state.milliSecondsElapsed).slice(-2);
}
// var number = this.state.milliSecondsElapsed.toString().length;
getSeconds() {
var milli = this.state.milliSecondsElapsed;
var seconds = 0;
seconds = milli / 100;
var myTrunc = Math.trunc(seconds);
myTrunc = myTrunc % 60;
return ("0" + myTrunc).slice(-2);
}
getMinutes() {
var milli = this.state.milliSecondsElapsed;
var seconds = 0;
var minutes = 0;
seconds = milli / 100;
minutes = seconds / 60;
var myTrunc = Math.trunc(minutes);
return ("0" + myTrunc).slice(-2);
}
handleStartClick = () => {
this.setState({
milliSecondsElapsed: (0)
});
this.timer = setInterval(() => {
this.setState({
milliSecondsElapsed: (this.state.milliSecondsElapsed + 1)
});
}, 10)
}
handleStopClick = () => {
clearInterval(this.timer);
}
render() {
return (
<div>
<h1>{this.getMinutes()}:{this.getSeconds()}.{this.getMilliseconds()}</h1>
<button type="button" onClick={this.handleStartClick}> start </button>
<button type="button" onClick={this.handleStopClick}> stop </button>
<input value={this.state.milliSecondsElapsed} onKeyDown={this.keyPress} onChange={this.handleStopClick}/>
</div>
);
}
}
export default Home;
Does anyone see what could be causing this?