admin管理员组

文章数量:1426120

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.

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.

Share Improve this question edited May 8, 2015 at 16:02 Jonny C 1,9413 gold badges21 silver badges38 bronze badges asked May 8, 2015 at 15:52 Giovanni Le GrandGiovanni Le Grand 7847 silver badges19 bronze badges 1
  • i would go with moment.js or some library, this is too primitive with setInterval – Vitaliy Terziev Commented May 8, 2015 at 16:02
Add a ment  | 

2 Answers 2

Reset to default 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);

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);
});  

本文标签: javascriptUpdating time span with jqueryStack Overflow