30 Days Of JavaScript

Day 23: Timer

Lesson 4: Timer: 4

Let's think about when we want these buttons to be enabled/disabled.

StateStartStopReset
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.

  1. Add setButtons("clear"); to the end of resetTimer().

  2. Add setButtons("stopped"); to the end of stopTimer().

  3. Add setButtons("running"); to the end of startTimer().

And now have a play around. Much better right?

Well almost, there's one more thing to fix.

Outline

Go Pro?

Upgrade to Pro for quizzes, tracked progress and a completion certificate for just $25 🚀

Want more developer tips, tricks and tools?
Then follow me:
FREE Coding Career Quick Start Guide 🚀
Discover the best way to learn to code, how to land a job and valuable resources to help your journey in this free 15 page value packed guide.
Looking to email me? You can get me on my first name at allthecode.co