晚上写一个chrome的小插件,碰到setInterval的问题,下面是可以实时显示时钟的:
function my_clock() {
var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var time;
minute = (minute < 10) ? ("0" + minute) : minute;
second = (second < 10) ? ("0" + second) : second;
time = hour + ":" + minute + ":" + second;
document.getElementById("clock_div").innerHTML = time;
}
setInterval(function() {
my_clock()
}, 1000);
但是之前的代码放在while循环里就不对了:
function my_clock() {
var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var time;
minute = (minute < 10) ? ("0" + minute) : minute;
second = (second < 10) ? ("0" + second) : second;
time = hour + ":" + minute + ":" + second;
document.getElementById("clock_div").innerHTML = time;
}
while(1){
setTimeout(function() {
my_clock()
}, 1000);
}
while(1)改成for循环发现反复调用setTimeout但不进入my_clock()