For this assignment, you will write a timer application in HTML and JavaScript.
Your HTML document should contain the following elements/features:
<html>
<head>
<title>
Timer
</title>
</head>
<body>
<label for="seconds">
<input type="number" id="seconds" value="0"/>
</label>
<button id="start">
Start
</button>
<script>
var button;
function addButtonToListenClick() {
// Taking reference to start button
button = document.getElementById("start");
// adding an event to button so when button clicked a function
handleStartClick called
button.addEventListener("click", handleStartClick);
}
addButtonToListenClick();
// in this function we remove tag start timer and create
tag
function handleStartClick() {
// taking reference to input
let input = document.getElementById("seconds");
// reading input value and converting it to number
let seconds = Number(input.value);
// remove input tag
input.remove();
// remove start button
button.remove()
// creating new p tag for timer
let pTag = document.createElement('p');
// giving paragraph an id
pTag.setAttribute("id", "timer");
// writing initial start time of time then we decrease it every
second upto 0
pTag.innerHTML = seconds;
// adding our timer paragraph to body
document.body.appendChild(pTag);
/**
* starting timer
*/
// we user interval to stop timer on 0. It stores reference to our
interval
let interval = null;
// setInterval calls function ( as first parameter) at every 1
second as described by second parameter 1000 ( ms ).
interval = setInterval(
function() {
// decreasing time on every call
seconds -= 1;
// showing latest time in paragraph
pTag.innerHTML = seconds;
// stop timer on reaching 0
if(seconds <= 0) {
clearInterval(interval)
// Recreating input tag and button
pTag.remove();
let inputTag = document.createElement('input');
// giving input same id timer
inputTag.setAttribute("id", "seconds");
inputTag.setAttribute("type", "number");
inputTag.value = 0;
document.body.appendChild(inputTag);
let buttonTag = document.createElement('button');
// giving button same id start
buttonTag.setAttribute("id", "start");
buttonTag.setAttribute("type", "button");
buttonTag.innerHTML = "New Timer";
document.body.appendChild(buttonTag);
addButtonToListenClick();
}
}, 1000
)
}
</script>
</body>
</html>
Get Answers For Free
Most questions answered within 1 hours.