douduan9129 2015-02-24 15:55
浏览 45
已采纳

达到0时停止Jquery计时器

I am in need of help. I am making a count down script for my game website which grabs the end time from the database and counts down until the current time is equal to the database time. But I can not seem to get it to stop when it hits 0. I have looked into setTimeout() and I do not understand how I would get this to work.

Also when the page is refreshed it starts the timer again from the database time. How would i either, update the database to the time left or stop the timer from refreshing.

Thanks in adavance. Below is the script I have so far

<?php
include "header.php";

?>
 <html>
<head>
<script type="text/javascript">
var curTime = Math.floor( (new Date()).getTime() / 1000 ); // replaced with PHP time(), presumably
var endTime = Math.floor( (new Date()).getTime() / 1000 ) + <?php echo $user_class->jail;?>;

function tick( )
{
    var secs = endTime - cTime;
    var mins = Math.floor( secs / 60 );
    secs %= 60;
    document.getElementById("ticker").innerHTML = 
         mins + " minutes, " + secs + " seconds";
    ++curTime;
}
</script>
</head>
<body onload="setInterval(tick,1000); tick();">
<h3>Time remaining is <span id="ticker"></span></h3>

</body>
</html>

My database is currently updated every 1 minute through a cron so it can be out due to the cron. But I was wondering if there was a way to update the database through the countdown instead so it will be acurate as other the timer

  • 写回答

4条回答 默认 最新

  • doufeng3602 2015-02-24 16:03
    关注

    Put this if() at the end of your tick() function

    if(endTime < curTime) clearInterval(i);
    

    And change your onload value to this.

    <body onload="i = setInterval(tick,100); tick();">
    

    clearInterval should make the job. Be carefull with this line

    var secs = endTime - cTime;
    

    Which probably contains a typo on your cTime var

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

报告相同问题?

悬赏问题

  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题