-2

So I am getting the new time but instead of updating it, it just writes the time again and again on the screen. I researched on how to set the interval and this was the way I found. I am trying to learn html and javascript, so I am sorry for not understanding how to fix this.

Here is the part in my html code where I call it from the js file. Id="time" is the javascript code for the current time.

    <div id="top">
            <span id="quote"><script type="text/javascript" src="quote.js"></script></span>
            <span id="date"><script type="text/javascript" src="date.js"></script></span>
            <span id="time"><script type="text/javascript" src="time.js"></script></span>
    </div>

Here is the javascript code for the time.

function time(){
var currentDate = new Date();
var hour = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
var time = hour + ":" + minutes + ":" + seconds;
document.write(time);
}
setInterval(function(){time()},1000);

As you can see it paints the time 1:02 1:03 1:04.......

Thank you so much for the help!

1 Answers1

4

First, there is no reason to put your <script> tags in <span> tags. Instead, put them just before the closing </body> tag.

Second, do not use document.write() to update content. SEE: Why is document.write considered a "bad practice"?.

This would work for you:

<div id="time"></div>

function time(){
 var currentDate = new Date();
 var hour = currentDate.getHours();
 var minutes = currentDate.getMinutes();
 var seconds = currentDate.getSeconds();
 var time = hour + ":" + minutes + ":" + seconds;

 //get the time div
 var timeDiv = document.getElementById("time");
 timeDiv.innerHTML = time; //set the content of time div to current time
 }
 setInterval(function(){time()},1000);
Community
  • 1
  • 1
Akinkunle Allen
  • 1,249
  • 11
  • 18