倒计时setInterval过快

时间:2017-05-01 17:20:22

标签: javascript jquery setinterval

有人可以帮助我吗,我想知道怎么做才能让点击每次点击都不会更快?我假设间隔清楚但不确定我需要放什么。谢谢



var cD = 100;

function countDown() {
    if (cD > 0) {
        cD -= 1;
        $(".countdown").html(cD +"s");
    }
}

$(".countdown-trigger").click(function(){
    cD = 100;

    setInterval(countDown, 10);
});

.countdown-trigger {
    height: 50px;
    width: 100px;
    background-color: blue;
}

.countdown {
    font-family: "Teko", sans-serif;
    font-size: 100px;
    line-height: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
    </div>
    <div class="countdown-trigger">
    </div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

问题是因为你从不清除每次连续点击的上一次超时,因此在3次点击后你有三个定时器,每10ms减少一次。

要在clearTimeout()点击cD时修正此致电0。另请注意,您需要一种机制来防止在前一个间隔仍在运行时启动多个间隔,否则您将遇到相同的问题。为此,您可以使用布尔标志。试试这个:

&#13;
&#13;
var cD = 100, interval, running = false;

function countDown() {
  if (cD > 0) {
    cD -= 1;
    $(".countdown").html(('00' + cD).slice(-2) + "s");
  } else {
    clearInterval(interval);
    running = false;
  }
}

$(".countdown-trigger").click(function() {
  if (running)
    return;
    
  cD = 100;
  running = true;
  interval = setInterval(countDown, 10);
});
&#13;
.countdown-trigger {
  height: 50px;
  width: 100px;
  background-color: blue;
}

.countdown {
  font-family: "Teko", sans-serif;
  font-size: 100px;
  line-height: 100px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div>
<div class="countdown-trigger"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

var cD = 100;
var myOtherVar;

function countDown() {
    if (cD > 0) {
        cD -= 1;
        $(".countdown").html(cD +"s");
    } else {
        clearInterval(myOtherVar);
    }
}

$(".countdown-trigger").click(function(){
    cD = 100;

    myOtherVar = setInterval(countDown, 10);
});
.countdown-trigger {
    height: 50px;
    width: 100px;
    background-color: blue;
}

.countdown {
    font-family: "Teko", sans-serif;
    font-size: 100px;
    line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
    </div>
    <div class="countdown-trigger">
    </div>

你是对的。你只需要清除你的间隔。每次点击该区域,它都会设置另一组每10毫秒发生一次的事件。这就是为什么它继续变得更快&amp;更快。