如何让setInterval倒计时工作?

时间:2014-11-15 04:39:19

标签: javascript jquery

我无法让这个倒计时工作。如何让它倒计时?

如果我想让它计数,我该怎么做呢?

jsfiddle:http://jsfiddle.net/vx16tnet/2/

jquery的:

$('.count').on('click', function(){
    var countDown = $('.count').text();
    console.log(countDown);

    setInterval(function() {
        countDown--;
        $('.count').html(countDown);
    }, 1000);
});

4 个答案:

答案 0 :(得分:1)



$('.count').on('click', function() {
  var count = $(this);
  var countDown = parseInt(count.text()) || 0;
  var timer = setInterval(function() {
    if (!countDown) {
      clearInterval(timer);
    }
    count.text(countDown--);
  }, 50);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="count" title="Click to start">10</span>
<span class="count" title="Click to start">100</span>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

假设您希望每隔1.523秒将0.001的浮点数减去1

Fiddle

function myfunction() {

    setInterval(function(){
        var current = $('.number').text();
        console.log('the value is ' + current);
        var newNumb = Math.round((parseFloat(current) - 0.001) * 1000) / 1000;
        $('.number').html(newNumb);
        console.log(newNumb);
    }, 1000);
}
$(document).ready(function(){
    myfunction();
});

答案 2 :(得分:0)

在myfunction()上调用setinterval而不是在其中

function myfunction() {
    var current = $('.number').text();
        console.log('the value is ' + current);

       var newNumb = parseFloat(current) + 1;

        $('.number').html(newNumb);
        console.log(newNumb);

}
$(document).ready(function(){
    setInterval(function(){ myfunction();}, 2000);
});

答案 3 :(得分:0)

倒数:     var clock = 10;

var countdownId = 0;



function start() {

    //Start clock

    countdownId = setInterval("countdown()", 1000);

}



function countup(){

    if(clock > 0){

        clock = clock+ 1;

        document.getElementById('cdDiv').innerHTML = clock;

    }

else {

    //Stop clock

        clearInterval(countdownId);

}

function countdown(){

    if(clock > 0){

        clock = clock - 1;

        document.getElementById('cdDiv').innerHTML = clock;

    }

else {

    //Stop clock

        clearInterval(countdownId);

}
}