Skip to content

Instantly share code, notes, and snippets.

@MartaJank
Forked from ross-u/clock.js
Created November 17, 2020 15:22
Show Gist options
  • Save MartaJank/39f6bec3c4faa894bfa5951f6a5b4039 to your computer and use it in GitHub Desktop.
Save MartaJank/39f6bec3c4faa894bfa5951f6a5b4039 to your computer and use it in GitHub Desktop.
Clock & setInterval example - 2020 mar
// Get the DOM elements
const stopButton = document.querySelector("#stop-btn");
const h1Tag = document.querySelector("h1");
const second = 1000;
// Formats one digit number to a string with "0"
function concatZero (num){ // 1 22
return ('0' + num ).slice(-2); // "01" "22"
}
function updateClock() {
// Instantiate new object Date object, representing the current system time
const dateObj = new Date();
// Get the hours, minutes and seconds from the date object
const hours = dateObj.getHours();
const minutes = dateObj.getMinutes();
const seconds = dateObj.getSeconds();
const milliseconds = dateObj.getMilliseconds();
// Create a string representing the time
const timeNow = `${concatZero(hours)} : ${concatZero(minutes)} : ${concatZero(seconds)} : ${milliseconds}`;
// console.log(timeNow);
// Set the content of the h1 element
h1Tag.innerHTML = timeNow;
}
const intervalId = setInterval(updateClock, second);
//const intervalId = setInterval(updateClock, 1);
stopButton.addEventListener('click', function() {
clearInterval(intervalId);
});
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<title>Asynchronous JS</title>
</head>
<body>
<h1></h1>
<button id="stop-btn">Stop</button>
<script src='./clock.js'></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment