en.javascript.info/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.view/index.html
2018-10-07 19:05:45 +03:00

64 lines
1.3 KiB
HTML

<!DOCTYPE HTML>
<html>
<head>
<style>
.hour {
color: red
}
.min {
color: green
}
.sec {
color: blue
}
</style>
</head>
<body>
<div id="clock">
<span class="hour">hh</span>:<span class="min">mm</span>:<span class="sec">ss</span>
</div>
<script>
let timerId;
function update() {
let clock = document.getElementById('clock');
let date = new Date();
let hours = date.getHours();
if (hours < 10) hours = '0' + hours;
clock.children[0].innerHTML = hours;
let minutes = date.getMinutes();
if (minutes < 10) minutes = '0' + minutes;
clock.children[1].innerHTML = minutes;
let seconds = date.getSeconds();
if (seconds < 10) seconds = '0' + seconds;
clock.children[2].innerHTML = seconds;
}
function clockStart() {
timerId = setInterval(update, 1000);
update(); // <-- start right now, don't wait 1 second till the first setInterval works
}
function clockStop() {
clearInterval(timerId);
}
clockStart();
</script>
<!-- click on this button calls clockStart() -->
<input type="button" onclick="clockStart()" value="Start">
<!-- click on this button calls clockStop() -->
<input type="button" onclick="clockStop()" value="Stop">
</body>
</html>