3

我正在尝试创建一个简单的 3-2-1 计数器。我想显示 3、2 和 1,并在倒计时结束时运行一个函数。我尝试了几件事无济于事:

$("#count_num").delay(1000).queue(function() {
        $(this).html("2")
        });
$("#count_num").delay(1000).queue(function() {
        $(this).html("1")
        });

和:

$("#count_num").delay(1000).queue(function() {
        $(this).html("2").delay(1000).queue(function() {
        $(this).html("1")
        });
        });

在这些情况下,它确实达到 2 但永远不会达到 1。我还安装了 doTimeout 插件(http://benalman.com/projects/jquery-dotimeout-plugin/)并尝试了这个:

$.doTimeout( 1000, function(){
        $("#count_num").html("2");
        });
$.doTimeout( 1000, function(){
        $("#count_num").html("1");
        });

和:

var count=3;
        $.doTimeout( 1000, function(){
        if ( count==1 ) {
        // do something finally
        return false;
        }
        $("#count_num").html(count);
        count--;
        return true;
        });

我究竟做错了什么?谢谢。

4

4 回答 4

8
function endCountdown() {
  // logic to finish the countdown here
}

function handleTimer() {
  if(count === 0) {
    clearInterval(timer);
    endCountdown();
  } else {
    $('#count_num').html(count);
    count--;
  }
}

var count = 3;
var timer = setInterval(function() { handleTimer(count); }, 1000);

不使用 jQuery,但应该可以正常工作。

于 2011-04-09T17:32:22.500 回答
3
var timer = setInterval(function(){
$("#count_num").html(function(i,html){
   if(parseInt(html)>0)
   {
   return parseInt(html)-1;
   }
   else
   {
   clearTimeout(timer);
   return "KO!!";
   }
 });

},1000);

这是一个*示例*

于 2011-04-09T17:31:34.777 回答
2

您不需要为此使用插件。使用 JavaScript,您可以:

var count = 4;
function anim() {
    if (count > 0) {
        console.log(count);
        count--;
        setTimeout(anim, 700);
    }
    else {
        alert('end of counting')
    }
}
anim();

这将从 4 开始倒计时,然后在 count 达到 0 时执行一个函数。

在http://jsfiddle.net/GSWRW/检查工作示例

于 2011-04-09T19:08:03.963 回答
2

我制作了一个小 jquery 插件,它完全符合您的要求:

http://plugins.jquery.com/project/countTo

https://github.com/bartrail/jQuery.countTo

于 2011-09-02T15:08:12.130 回答