setInterval() timer not working

荒凉一梦 提交于 2021-02-11 17:47:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!