The remaining requirements from the last session are:
- Refactoring the two buttons to just one for starting/stopping the timer
- Being able to capture snapshots of the timer countdown on a button press.
- Clearing the snapshots and resetting the timer on another button press.
Refactoring the two buttons to a single one which would handle the starting and stopping of the timer proved to be tricky. For the single buttons Start and Stop a reference to the calling object itself was passed to the function and based on the innerHTML of that object, the button, the code would start or stop the timer.
When only one button was present, there was nothing that could be used to identify what ‘state’ the timer, by extension the button, was in. Tried one or two ways to sort this but most of them resulted in the single button functioning once to start/stop the timer but after that it wouldn’t function at all.
What finally did it was the creation of a Boolean to keep tabs of whether the button was clicked. Simple but boy did it take some time getting to it. [see commit]
With that out of the way the only thing left to do was to capture the counter values and show them beneath the actual counter and reset the captured values and timer count. This was simple enough and only required adding to the innerHTML of the display area and clearing them. [see commit]
One final item remaining was to enable key presses to activate the same functions as the button presses. These were:
- ‘s’ to start and stop the timer
- ‘t’ to record the times
- ‘r’ reset the recorded times and timer
This presented some challenges as I wasn’t too sure how the code would be invoked from a separate script file. I thought it would have to go in the actual HTML document. But referring to the document element from the script file and adding an event listener to it did the trick.
From there it was just a simple callback function, part of which can be see above, with the event object passed to it from which the keypresses could be retrieved.
And there you have it, another successful simple project completed. You can see it in action here https://donyd.github.io/Simple-Timer/
There was one final issue, this time with Github. You can see the code at various iterations of the work in progress, however the final Github page only shows the final results.
Catch up with the initial posts about this piece: