0

Can someone help me with what is the best away to make a div reload? for example a div with a timer.

Exemple:

<div id="clock"> 00:00:00 </div>

And i need that to reload every 1s like

<div id="clock"> 00:00:00 </div>
<div id="clock"> 00:00:01 </div>
<div id="clock"> 00:00:02 </div>
<div id="clock"> 00:00:03 </div>
JoseM
  • 4,302
  • 2
  • 24
  • 35
Richard
  • 17
  • 6

2 Answers2

3

You can do something like this:

window.setInterval(function(){
  /// Update the div
  document.getElementById("clock").innerHTML = "the new value";
}, 1000);

This is going to set a new content to the div every second (1000 miliseconds)

Fernando Garcia
  • 1,946
  • 2
  • 12
  • 14
3

If you want to use javascript to make a "timer-like" updating div, in an hh:mm:ss format, you can use setInterval and a parsing function (taken from @powtac's answer here):

var startTime = 0;

window.setInterval(function() {
  $("#clock").html(toHHMMSS(startTime.toString()));
  startTime++;
}, 1000);


function toHHMMSS(str) {
  var sec_num = parseInt(str, 10); // don't forget the second param
  var hours = Math.floor(sec_num / 3600);
  var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
  var seconds = sec_num - (hours * 3600) - (minutes * 60);

  if (hours < 10) {
    hours = "0" + hours;
  }
  if (minutes < 10) {
    minutes = "0" + minutes;
  }
  if (seconds < 10) {
    seconds = "0" + seconds;
  }
  var time = hours + ':' + minutes + ':' + seconds;
  return time;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="clock">00:00:00</div>
Community
  • 1
  • 1
wahwahwah
  • 3,254
  • 1
  • 21
  • 40