jQuery的倒数计时器停止在零

时间:2019-07-20 12:02:50

标签: jquery

我正在使用jquery从5秒倒数到零,我的倒数计时工作正常,但是它无限执行,我做了if语句,所以如果dro命中0,我想停止计时器,但不知道如何停止它,我尝试了clearinterval但没有任何解决方案?

    var dro = 5;
    var saboloo = 0;
    function setup(){
        var es = $('#dro');
        dro--;
        es.html(dro);
        if(dro == 0){
            es.html(clearInterval(setup));
        }
    }
    setInterval(setup,1000);
<h1 class="wait"><span value="5" id="dro">5</span>Seconds before the game starts</h1>

3 个答案:

答案 0 :(得分:2)

该间隔没有参考,因此以后无法清除。您正在尝试清除print (df.loc[pd.Timestamp(a.index.item()): pd.Timestamp(b.index.item())]) 的间隔,但这不是间隔引用。 setup只是您在每个setup上调用的函数。

因此,您可以创建对interval的正确引用,并在以后用于setInterval

让我们将其放在clearInterval上并命名为variable

setupInterval

答案 1 :(得分:1)

我会使用:

var dro = 5;
function setup(){
    var es = $('#dro');
    if(dro > 0){
        dro--;
        es.html(dro);
        let t = setTimeout(function(){
            setup();
        }, 1000);
    }
    else{
        es.html('game started');
    }
}
setup();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<h1 class="wait"><span value="5" id="dro">5</span>Seconds before the game starts</h1>

答案 2 :(得分:1)

您并没有真正“清除间隔”,因为您甚至没有将setInterval分配给变量,也没有清除函数(setup)。

情况如何:

  • 声明一个变量,该变量保留剩余的秒数。
  • 声明另一个变量来保存“时间间隔”,以便我们稍后可以清除它。
  • 用剩余的秒数更新span,同时减少保存剩余秒数的变量。
  • 如果该变量已达到零,请清除间隔。

下一个示例说明了正在说的内容:

let remSec = $("#count"),
  /** referencing the "span" element **/
  countSec = 4,
  /** 
  * number of the remaining seconds. Change this per your requirements.
  * Equals to 4 as we'll have "(4 - 0) + 1" seconds to write which equals 5 (because the second number 0 is also included).
  **/
  /** the interval is assigned to "timer" variable so we'll be able to stop it later **/
  timer = setInterval(() => {
  /** if the seconds hasn't yet reached zero ==> write it the span. Else clear the interval **/
  countSec >= 0 ? remSec.text(countSec--) : clearInterval(timer); /** we're writing the seconds in the  span along with decreasing the "countSec" variable value at the same time note the "--" that means post decrement (use the variable then decrease one from its value) **/
  }, 1000); /** the function runs for every second till the interval is cleared **/
<!-- for demo purposes, the "span" will hold the number of seconds -->
<div>countdown: <span id="count">5</span> seconds left.</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

如果需要,您可以检查my answer是否有另一个类似的问题。

希望我进一步推动了你。