Created
January 5, 2019 06:13
-
-
Save twhite96/ae58313f297ca264ea6901ffb146cfe1 to your computer and use it in GitHub Desktop.
Stopwatch full updater
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StopWatch extends React.Component { | |
state = { lapse: 0, running: false }; | |
handleRunClick = () => { | |
//updater function | |
this.setState(state => { | |
if (state.running) { | |
clearInterval(this.timer); | |
} else { | |
const startTime = Date.now() - this.state.lapse; | |
this.timer = setInterval(() => { | |
this.setState({ | |
lapse: Date.now() - startTime | |
}); | |
}); | |
} | |
// returning a new state to not mutate our original state | |
return { running: !state.running }; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment