Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a live clock in javascript

The clock kinda works. But instead of replacing the current time of day it prints a new time of day every second. I understand why it do it but I don't know how to fix it. I would appreciate if you could give me some tips without saying the answer straight out. Thank you. Here is my code:

function time(){
    var d = new Date();
    var s = d.getSeconds();
    var m = d.getMinutes();
    var h = d.getHours();
    document.write(h + ":" + m + ":" + s);
}

setInterval(time,1000);
like image 707
WilliamG Avatar asked Sep 09 '16 19:09

WilliamG


People also ask

How do you make a live clock in JavaScript?

Javascript Clock Code (12 hours): function currentTime() { let date = new Date(); let hh = date. getHours(); let mm = date. getMinutes(); let ss = date. getSeconds(); let session = "AM"; if(hh == 0){ hh = 12; } if(hh > 12){ hh = hh - 12; session = "PM"; } hh = (hh < 10) ?

How do I add real time in HTML?

JavaScript Date Object + HTML, JS codeCurrent Date and Time is stored inside javascript variable. Then using TextContent property the content of HTML span element is set with current and time. Unique ID is given to span tag so that we can use it on getElementById() method to dispaly the current date and time.

How do I show date and time in HTML?

The <time> datetime Attribute in HTML is used to defines the machine-readable date/time of the <time> element. The date-time is inserted in the format YYYY-MM-DDThh:mm:ssTZD.

How do I display the date in HTML?

HTML <input type="date">


1 Answers

Add a span element and update its text content.

var span = document.getElementById('span');

function time() {
  var d = new Date();
  var s = d.getSeconds();
  var m = d.getMinutes();
  var h = d.getHours();
  span.textContent = 
    ("0" + h).substr(-2) + ":" + ("0" + m).substr(-2) + ":" + ("0" + s).substr(-2);
}

setInterval(time, 1000);
<span id="span"></span>

Answer updated [2021] https://stackoverflow.com/a/67149791/7942242

like image 54
Pranav C Balan Avatar answered Oct 14 '22 10:10

Pranav C Balan