Compte à rebour / Chronomètre
Démo
h m s
Source
<style>
#demo {
background: #eee;
padding: .5rem;
border-radius: 0.25rem;
text-align: center;
}
input[type=text] {
padding: .2rem;
border: 1px solid #a5a4a4;
border-radius: 0.25rem;
height: 1.5rem;
}
input[type=button], input[type=submit], input[type=reset] {
border: none;
color: #FFF;
background: #963c7b;
margin: .5rem 0;
padding: .5rem;
cursor: pointer;
text-decoration: none;
color: #FFF;
border-radius: 0.25rem;
}
</style>
<div id="demo">
<label for="countdown">Compte à rebour</label>
<input type="radio" name="type" value="0" id="countdown" checked onchange="setChoice(0)" />
<label for="stopwatch">Chronomètre</label>
<input type="radio" name="type" value="1" id="stopwatch" onchange="setChoice(1)" />
<br/>
<input type="text" class="text-center" id="h" value="0" size="3"> h
<input type="text" class="text-center" id="m" value="0" size="3"> m
<input type="text" class="text-center" id="s" value="0" size="3"> s
<br/>
<input type="button" value="Démarrer" onclick="start()" id="btn" />
</div>
<script>
var choice = 0;
var isPause = true;
var total = 0;
var cdTimeout = 0;
var flTimeout = 0;
var fl = 10;
//Start/pause
function start() {
if (isPause) {
isPause = false;
setValue("btn", "Pause");
var h = getValue("h");
var m = getValue("m");
var s = getValue("s");
total = s + m * 60 + h * 60 * 60;
count();
} else {
isPause = true;
setValue("btn", "Démarrer");
clearTimeout(cdTimeout);
}
}
//count
function count() {
if (total === 0 && choice === 0)
end();
else {
if (choice === 0)
total = total - 1;
else
total = total + 1;
update();
cdTimeout = setTimeout(count, 1000);
}
}
//Update input and title
function update() {
var h = Math.floor(total / 3600);
var r = total % 3600;
var m = Math.floor(r / 60);
var s = r % 60;
setValue("h", h);
setValue("m", m);
setValue("s", s);
document.title = "Timer - " + h + ":" + m + ":" + s;
}
//End of timer
function end() {
clearTimeout(cdTimeout);
setValue("btn", "Démarrer");
document.title = "Timer - FIN";
flash();
}
//Flash background color
function flash() {
if (fl > 0) {
if (fl % 2 === 0)
color = "#65054f";
else
color = "#eeeeee";
document.getElementById("demo").style.background = color;
fl = fl - 1;
flTimeout = setTimeout(flash, 200);
} else {
fl = 10;
clearTimeout(flTimeout);
}
}
//Set choice, countdown or stopwatch
function setChoice(c) {
console.log(c);
choice = c;
}
//Get value from input
function getValue(id) {
val = document.getElementById(id).value;
if (val != "")
val = parseInt(val);
else
val = 0;
return val;
}
//Set input value
function setValue(id, val) {
document.getElementById(id).value = val;
}
</script>