Lesson 4 - Challenge 2 - SOLUTION

by nathanesa

HTML

<div id='container'>

  <br>
  <div id='display'>
  0 : 00
  </div>
  <br>

  <div id='buttons'>
    <button class='myButton' onclick='start()'>START</button>
    <button class='myButton' onclick="stop()">STOP</button><br>
    <button class='myButton' onclick="reset()">RESET</button>
  </div>  

</div>

CSS

@import url('https://fonts.googleapis.com/css2?family=Major+Mono+Display&display=swap');

body {
  background-color: #445;
}

div {
  text-align: center;
  font-size: 40px;
  font-family: 'Major Mono Display', sans-serif;
}

#container {
  background-color: white;
  margin-top: 200px;
  border: solid;
  border-radius: 10px;
  width: 250px;
  height: 250px;
  margin-left: auto;
  margin-right: auto;
}

.myButton {
  box-shadow: inset 0px 1px 3px 0px #91b8b3;
  background: linear-gradient(to bottom, #768d87 5%, #6c7c7c 100%);
  background-color: #768d87;
  border-radius: 5px;
  border: 1px solid #566963;
  display: inline-block;
  cursor: pointer;
  color: #ffffff;
  font-family: Arial;
  font-size: 15px;
  font-weight: bold;
  padding: 11px 23px;
  text-decoration: none;
  text-shadow: 0px -1px 0px #2b665e;
}

.myButton:hover {
  background: linear-gradient(to bottom, #6c7c7c 5%, #768d87 100%);
  background-color: #6c7c7c;
}

.myButton:active {
  position: relative;
  top: 1px;
}

JavaScript

let seconds = 0;
let minutes = 0;
let timer;

// Formats the seconds to show two digits.
function formatSeconds() {
	if (seconds < 10) {
  	return "0" + seconds;
  }
  return seconds;
}

// Updates the time by increasing the number of seconds by 1, then displaying the new time.
function updateTime() {
  seconds = seconds + 1;
  if (seconds > 59) {
  	minutes = minutes + 1;
    seconds = 0;
  }
  document.getElementById('display').innerHTML = minutes + ' : ' + formatSeconds();
}

// Starts the stopwatch.
function start() {
	timer = setInterval(updateTime, 1000);
}

// Pauses the stopwatch.
function stop() {
 	clearInterval(timer);
}

// Sets the time back to 0.
function reset() {
	seconds = 0;
	minutes = 0;
  document.getElementById('display').innerHTML = minutes + ' : ' + seconds;
}