I am trying to create a countdown timer that counts down from an hour if a user enters 1 or 2 hours if a user enters 2, etc.. I know I need to multiply the value I am getting from the user by 60 in order to switch from calculating minutes and seconds from the input to calculating by hour but I am just not quite sure where to do so.
<script>
function startTimer() {
userInput = document.getElementById('userTime').value;
if(userInput.length == 0){
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
if(!userInput.match(numericExpression)){
alert("Please enter a number")
} else {
function display( notifier, str ) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond( x ) {
return Math.floor(x/60) + ":" + x%60;
}
function setTimer( remain, actions ) {
(function countdown() {
display("countdown", toMinuteAndSecond(remain));
actions[remain] && actions[remain]();
(remain -= 1) >= 0 && setTimeout(arguments.callee, 1000);
})();
}
setTimer(userInput, {
10: function () { display("notifier", "Warning message 1", document.bgColor="#ffff00"); },
5: function () { display("notifier", "Warning message 2", document.bgColor="#ff69b4"); },
0: function () { display("notifier", "Final message", document.bgColor="#ff0000"); }
});
}
}
}
</script>
<div id="countdown"></div>
<div id="notifier"></div>
<p>
Please Enter A Time Limit for the Meeting: <input type="text" id="userTime" />
<input type="button" value="Go" onclick="startTimer()" />
</p>
All you really need to change is your toMinuteAndSecond
function, which I have renamed and done below:
userInput = document.getElementById('userTime').value;
if (userInput.length == 0) {
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
if (!userInput.match(numericExpression)) {
alert("Please enter a number")
} else {
function display(notifier, str) {
document.getElementById(notifier).innerHTML = str;
}
function toFormattedHHMMSS(x) {
var hours = parseInt(x / 3600);
var minutes = parseInt(x / 60) % 60;
var seconds = x % 60;
return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
}
function setTimer(remain, actions) {
(function countdown() {
display("countdown", toFormattedHHMMSS(remain));
actions[remain] && actions[remain]();
(remain -= 1) >= 0 && setTimeout(arguments.callee, 1000);
})();
}
setTimer(userInput, {
10: function () {
display("notifier", "Warning message 1", document.bgColor = "#ffff00");
},
5: function () {
display("notifier", "Warning message 2", document.bgColor = "#ff69b4");
},
0: function () {
display("notifier", "Final message", document.bgColor = "#ff0000");
}
});
}
}
The same would be done for allowing days, or weeks, etc...