
Question: Create the behavior for a digital web stopwatch. Here are the action we are expecting: * When "Start" is clicked, the text "Stop Watch" should be replaced by "Time elapsed: 0", and the count should increment every second * When "Reset" is clicked, the text should return to "Stop Watch" * When "Pause" is clicked, the text should say "Time elapsed: 1", but stop incrementing
To solve this problem, we have to asses what steps we need to introduce.
- Create Javascript selectors that target each of the timer buttons.
- Create click handlers (empty, for now) for each of the timer buttons.
- Create the Callback functions for each click event for all three Buttons.
Here is the HTML code to access DOM.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Timer Test</title>
</head>
<body>
<h1 id="timer">Stop Watch</h1>
<div class="controls">
<button id="reset">Reset</button>
<button id="start">Start</button>
<button id="pause">Pause</button>
</div>
</body>
</html>
Now we can access DOM elements and Create the Callback functions based upon Click event!
'use strict';
const timer = (function() {
let seconds = 0;
let timerId;
let els;
let timerRunning = false;
const updateTime = () => {
seconds++;
els.timer.textContent = 'Time elapsed: ' + seconds;
};
const setupListeners = (elements) => {
els = elements;
els.start.addEventListener('click', () => {
console.log('start');
if(timerRunning) return;
timerRunning = true;
els.timer.textContent = `Time elapsed: ${seconds}`;
timerId = setInterval(updateTime, 1000);
});
els.pause.addEventListener('click', () => {
clearInterval(timerId)
timerRunning = false;
});
els.reset.addEventListener('click', () => {
console.log('reset');
seconds = 0;
clearInterval(timerId);
timerRunning = false;
els.timer.textContent = 'Stop Watch';
});
}
// return the closure
return { setupListeners };
})();
timer.setupListeners({
timer: document.querySelector('#timer'),
reset: document.querySelector('#reset'),
start: document.querySelector('#start'),
pause: document.querySelector('#pause'),
});