问题
This simple function is meant to display time and update every second using setInterval()
, the time is displaying but not updating, I have also tried calling the function from the body's onload call and it is the same.
<script language="JavaScript" type="text/javascript">
var currentTime = new Date();
function currentTimeStrings()
{
var hours = currentTime.getHours();
var hoursToString = hours;
if (hoursToString>12)
{
hoursToString = hoursToString-1;
}
switch (hoursToString)
{
case 13:
hoursToString = 2;
break;
case 14:
hoursToString = 3;
break;
case 15:
hoursToString = 4;
break;
case 16:
hoursToString = 5;
break;
case 17:
hoursToString = 6;
break;
case 18:
hoursToString = 7;
break;
case 19:
hoursToString = 8;
break;
case 20:
hoursToString = 9;
break;
case 21:
hoursToString = 10;
break;
case 22:
hoursToString = 11;
break;
case 23:
hoursToString = 12;
break;
default:
hoursToString = hoursToString;
break;
}
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
document.getElementById("timeDisp").innerHTML=hoursToString + ':' + minutes + ':' + seconds;
}
setInterval(currentTimeStrings,1000);
</script>
回答1:
Your currentTime
is created only once for the current time and never updated.
Try moving your var currentTime = new Date();
into inside the function:
function currentTimeStrings(){
var currentTime = new Date();
//your code
}
来源:https://stackoverflow.com/questions/21642176/setinterval-timer-not-working