1

I am trying to get a date to refresh on a page so I don't have to go and manually refresh it everyday. I have this code in place, but it doesn't seem to be working. The date displays, but it doesn't update when the day changes. For reference, this is being used on a BrightSign display. Can anyone tell me what I'm doing wrong? I'm kind of a JavaScript beginner so nothing too complex :)

<script type="text/javascript">
<!-- 
function clockTick()    {
   currentTime = new Date();
   month = currentTime.getMonth() + 1;
   day = currentTime.getDate();
   year = currentTime.getFullYear();
   setInterval(clockTick, 1000);
   return (month + "/" + day + "/" + year);
}
document.write(clockTick());
//-->
</script>
Legionar
  • 6,939
  • 2
  • 34
  • 66
Kristy Snyder
  • 23
  • 1
  • 5
  • 1
    [First you do not use document.write.](http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice), second, learn about setTimeout or setInterval – epascarello Dec 17 '14 at 13:38
  • If you want the date to refresh, you have to poll it with an interval and actually change it when the day changes. Is that what you want ? – adeneo Dec 17 '14 at 13:40

2 Answers2

1

You will want to take the setInterval out of the function and set the time on the page inside the function so that it refreshes every second:

function clockTick() {
  var currentTime = new Date(),
      month = currentTime.getMonth() + 1,
      day = currentTime.getDate(),
      year = currentTime.getFullYear(),
      hours = currentTime.getHours(),
      minutes = currentTime.getMinutes(),
      seconds = currentTime.getSeconds(),
      text = (month + "/" + day + "/" + year + ' ' + hours + ':' + minutes + ':' + seconds);
  // here we get the element with the id of "date" and change the content to the text variable we made above
  document.getElementById('date').innerHTML = text;
}

// here we run the clockTick function every 1000ms (1 second)
setInterval(clockTick, 1000);
<span id="date"></span>
Bill
  • 3,382
  • 20
  • 41
Tomanow
  • 6,810
  • 3
  • 22
  • 49
0

you can try this:call clockTick() from outside.

 function clockTick()    {
       currentTime = new Date();
       month = currentTime.getMonth() + 1;
       day = currentTime.getDate();
       year = currentTime.getFullYear();
      // alert("hi");
      document.getElementById('date').innerHTML=month + "/" + day + "/" + year;
    }
    
    setInterval(function(){clockTick();}, 1000);//setInterval(clockTick, 1000); will also work
<div id="date"></div>
Suchit kumar
  • 11,448
  • 3
  • 17
  • 41