douwen1549 2014-11-28 14:27 采纳率: 100%
浏览 52
已采纳

Javascript函数在单击按钮之前激活

If requirements are met when you click the button it will display a count down timer. Problem is it displays the countdown timer BEFORE you even click the button. I'm not sure what I'm overlooking.

 <input id="upgrade" type="button" value="Upgrade" onclick="timer();" />
 <br><br><br><br>
 <p id="countdown_timer"></p>

<script>
    function display_timer(){
        document.getElementById("countdown_timer").innerHTML = "<span id='countdown' class='timer'></span>";
    }
</script>

<script>
    var currently_upgrading = 0;
    var current_ore         = 398;
    var current_crystal     = 398;
    var upgradeTime  = 172801;
    var seconds      = upgradeTime;

    function timer() {
        if(currently_upgrading == 1){alert('You are already upgrading a module.');return;}
        if(current_ore <= 299){alert('You need more ore.');return;}
        if(current_crystal <= 299){alert('You need more crystal.');return;}

        display_timer();
        var days        = Math.floor(seconds/24/60/60);
        var hoursLeft   = Math.floor((seconds) - (days*86400));
        var hours       = Math.floor(hoursLeft/3600);
        var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
        var minutes     = Math.floor(minutesLeft/60);
        var remainingSeconds = seconds % 60;

        if (remainingSeconds < 10) {
            remainingSeconds = "0" + remainingSeconds; 
        }
        document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
        if (seconds == 0) {
            clearInterval(countdownTimer);
            document.getElementById('countdown').innerHTML = "Completed";
        } else {
            seconds--;
        }
    }
    var countdownTimer = setInterval('timer()', 1000);
</script>
  • 写回答

4条回答 默认 最新

  • dongque1646 2014-11-28 14:35
    关注

    Try changing the last lines of timer() to be like this:

        if (seconds == 0) {
            document.getElementById('countdown').innerHTML = "Completed";
        } else {
            seconds--;
            setTimeout(timer, 1000);
        }
    

    and remove the setInterval line.

    Speaking generally, setTimeout is much preferred to setInterval, because it doesn't require a managed state (countdownTimer in your example) and is far more flexible.

    Also note that passing a string as in setTimeout('timer()', 1000) is obsolete, just pass a function: setTimeout(timer, ...).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?