I'm trying to make a timer-based document that resets .it's countdown anytime I click the mouse or press a button on my keyboard. Due to my relative lack of knowledge in JavaScript however, I don't know what the next step is after making the timer
I'm pretty sure what I need to use is onkeyup
and onmouseup
events, but I'm unsure where to put them or what to add to them. Here's the code for the timer.
let mins = document.getElementById("minutes");
let secs = document.getElementById("seconds");
let display = document.getElementById("display");
let start = document.getElementById("start");
let timer;
function displaymin() {
display.innerHTML =
(minutes.value > 9 ? minutes.value : "0" + minutes.value) +
":" +
(seconds.value > 9 ? seconds.value : "0" + seconds.value);
}
function watch() {
start.disabled = true;
mins.disabled = true;
secs.disabled = true;
var date1 = new Date();
var countDownDate = new Date();
countDownDate.setTime(
date1.getTime() +
minutes.value * 60 * 1000 +
seconds.value * 1000 +
1 * 1000
);
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
display.innerHTML =
(minutes > 9 ? minutes : "0" + minutes) +
":" +
(seconds > 9 ? seconds : "0" + seconds);
var audio = new Audio("alarm.mp3");
if (display.innerHTML == "00:00") {
clearInterval(x);
audio.play()
}
}, 1000);
}
<div oninput="displaymin()">
<input type="number" id="minutes" min="0" max="59" placeholder="mins" /> :
<input type="number" id="seconds" min="0" max="59" placeholder="secs" />
</div>
<div id="display"></div>
<div>
<button id="start" onclick="watch()">Start</button>
</div>