2

I have a tiny script which should update a span with the current time.

This script works BEFORE the setInterval but not during the setInterval.

HTML:

<?= date("d/m/Y") ?> <span id="time"></span>

Javascript:

$(document).ready(function(){
    var dt = new Date();
    var time = dt.getHours() + ":" + dt.getMinutes();
    $("#time").text(time);
    setInterval(function(){
        console.log("interval");
        time = dt.getHours() + ":" + dt.getMinutes();
        $("#time").text(time);
    },5000);
});    

The span with id time just doesn't change the time.

Jonny C
  • 1,943
  • 3
  • 20
  • 36

2 Answers2

4

You need to set dt each time, the date object doesn't keep updating the time. It stays at the time it was created.

See this code and this fiddle

var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes();

$("#time").text(time);

setInterval(function(){

    dt = new Date();
    time = dt.getHours() + ":" + dt.getMinutes();

    $("#time").text(time);

},5000);
GillesC
  • 10,647
  • 3
  • 40
  • 55
  • thnx that worked now i only gotta know how to add a leading 0 if its beneith 10 :( – Giovanni Le Grand May 08 '15 at 16:02
  • 1
    Look here http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date Basically just add zero all the time then use slice to grab the last 2 characters and you always get what you want. – GillesC May 08 '15 at 16:17
3

You need to update the dt object too. Your getHours() and getMinutes() functions inside work on the dt object initialised before the setInterval(). If you do not re-init dt it will take the date of cached object.

setInterval(function(){
    console.log("interval");

    dt = new Date();                //here!

    time = dt.getHours() + ":" + dt.getMinutes();
    console.log(time)
    $("#time").text(time);
},5000);

Demo


Full code :

$(document).ready(function(){
    var dt = new Date();
    var time = dt.getHours() + ":" + dt.getMinutes();
    $("#time").text(time);
    setInterval(function(){
        console.log("interval");
        dt = new Date();
        time = dt.getHours() + ":" + dt.getMinutes();
        $("#time").text(time);
    },5000);
});  
Shaunak D
  • 20,588
  • 10
  • 46
  • 79