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
2 Answers
Reset to default 4You 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
版权声明:本文标题:javascript - Updating time span with jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745386005a2656378.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论