create a java script to allow a clock keeping time

  • Home
  • create a java script to allow a clock keeping time

create a java script to allow a clock keeping time

function clock() {
// get current time
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();

//format time to 12-hour clock
let amOrPm = hours >= 12 ? ‘PM’ : ‘AM’;
hours = hours % 12 || 12;

// add leading zeros for single digit numbers
if (hours < 10) { hours = '0' + hours; } if (minutes < 10) { minutes = '0' + minutes; } if (seconds < 10) { seconds = '0' + seconds; } // display time on webpage document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + amOrPm; // update time every second setTimeout(clock, 1000); } // call the clock function to start displaying time clock();

Archives

Categories

loader