setInterval()计时器不起作用

时间:2014-02-08 05:06:04

标签: javascript setinterval

这个简单的函数用于显示时间并使用setInterval()每秒更新,时间显示但不更新,我也尝试从正文的onload调用中调用函数,它是相同的。

<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 个答案:

答案 0 :(得分:3)

您的currentTime仅在当前时间创建一次,从未更新

尝试将var currentTime = new Date();移到功能内部:

function currentTimeStrings(){
   var currentTime = new Date();
   //your code
}