Day 23: Timer
Lesson 4: Timer: 4
Let's think about when we want these buttons to be enabled/disabled.
State | Start | Stop | Reset |
---|---|---|---|
Clear | ✅ | ❌ | ❌ |
Running | ❌ | ✅ | ❌ |
Stopped | ✅ | ❌ | ✅ |
Let's make a small function that can enable and disable our button depending on what state the timer is in.
Firstly add references to our button to the top of the JavaScript.
1const startButton = document.getElementById("start"); 2const stopButton = document.getElementById("stop"); 3const resetButton = document.getElementById("reset");
And now add this function to your JavaScript:
1function setButtons(state) { 2 if (state === "clear") { 3 startButton.disabled = false; 4 stopButton.disabled = true; 5 resetButton.disabled = true; 6 } 7 if (state === "running") { 8 startButton.disabled = true; 9 stopButton.disabled = false; 10 resetButton.disabled = true; 11 } 12 if (state === "stopped") { 13 startButton.disabled = false; 14 stopButton.disabled = true; 15 resetButton.disabled = false; 16 } 17}
Take a moment to read over that code and get your head around when we are enabling and disabling buttons.
Now we need to call setButtons()
with the correct state string to keep the buttons in sync.
Add
setButtons("clear");
to the end ofresetTimer()
.Add
setButtons("stopped");
to the end ofstopTimer()
.Add
setButtons("running");
to the end ofstartTimer()
.
And now have a play around. Much better right?
Well almost, there's one more thing to fix.