Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Resetting the Stopwatch2:45 with Guil Hernandez
In order to display the stopwatch time in seconds, we'll do one final calculation that converts the elapsed time in milliseconds to seconds. Then we'll wire up the "Reset" button to a function that resets the stopwatch back to 0.
In order to display the stopwatch time in seconds, we'll 0:00 do one final calculation that converts the elapsedTime in milliseconds to seconds. 0:03 For instance, if I display the time in render method with the jsx 0:07 expression this.state.elapsedTime, and click the Start button. 0:12 We see the time updating at 1,000 milliseconds per second. 0:17 To get the value in seconds, we need to divide elapsedTime by 1,000. 0:21 So inside the expression, 0:26 I'll write Math.floor to round the value down to its nearest integer. 0:28 That way we don't get a decimal value, 0:33 then divide this.state.elapsedTime by 1,000. 0:35 Back in the stopwatch, when I click the Start button, 0:39 we see the timer taking in seconds. 0:44 If I click Stop, the timer stops, and 0:47 clicking Start continues the timer from where it left off, good. 0:50 Sometimes the return statement holding our JSX can get messy with too many 0:54 expressions and logic. 0:58 When this happens, our code could become difficult to read, debug, and maintain. 0:59 Now, in our case, this isn't really an issue, but I'm going to make the code just 1:04 a little more organized by storing the Math.floor function and 1:08 calculation in a variable. 1:11 In the render method, 1:12 any intermediary variables should be written outside the return statement. 1:14 So I'll create a variable seconds, assign it the math.floor function, 1:18 then in the JSX expression, call the seconds variable. 1:26 Next, we'll wire up the Reset button to a function that resets 1:32 the stopwatch back to 0, this should be pretty straightforward. 1:37 Let's create a new function named handleReset. 1:42 In this function, we'll use this.setState to set the elapsedTime state back to 0. 1:51 And I won't update the is running state here because I 2:00 don't want to stop the timer when a user clicks Reset. 2:03 I'll keep the reset logic independent of the start and stop logic. 2:05 Finally, let's add an onClick event to the Reset button. 2:09 This onClick event needs to call the handleReset function, 2:14 so let's pass it this.handleReset. 2:18 Over in the browser, let's Start the stopwatch. 2:21 Now you can Stop it and Start it again, click Reset, and 2:26 it resets to 0 but continues to tick. 2:31 If you click Stop, you're able to reset it while stopped, then Start it up again. 2:34 All right, nice, now we have a functioning stopwatch. 2:43
You need to sign up for Treehouse in order to download course files.Sign up