简体   繁体   中英

Updating time span with jquery

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM