I'm trying to work out how when I press a key it counts down from 30 to 0, and if i press that key again it does the same thing, counts from 30 to 0 (resets).
Is there some way this is can be done with JavaScript and in the HTML only have it displaying the numbers counting from 30 to 0 with no other text?
I have tried using other examples however I think i must be putting the script into the wrong place. Is someone able to give me an example not just of the JS but also what the HTML markup should look like? Would be much appreciated.
The example I have been trying to modify and play with is:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
$(function() {
var perc = 50 // User will be logged out after (minutes)
var count = perc * 60;
// RESET TIMER
$(document).keypress(function() {
var count = perc * 60; // PROBLEM
alert('keypress works');
});
//COUNTDOWN
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count == -1) {
// LOGOUT //
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
seconds %= 60;
minutes %= 60;
document.getElementById("seconds").innerHTML = seconds;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("start_time").innerHTML = inactive;
};
});
</script>
</body>
</html>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…