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条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值