JavaScript/jQuery中的简单3-2-1倒计时

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个回答

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,但应该可以正常工作。


感谢您的回复。我尝试了这个方法,但它没有起作用。我在这里添加了一个警告: "else { $('#count_num').html(count); count--; alert(count); }" 它会到2,但是一直重复2(永远不会到1)。 - vee
抱歉,我给 handleTimer 加了一个参数,但它不应该有参数。现在请尝试(更新后的答案)。 - EMMERICH

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);

这是一个*示例*


这个程序可以工作,但是它不会在0处停止,而是会继续进入负数-1、-2等,如何才能在0处停止呢? - Dizzi

2
你不需要使用插件来实现这个功能。你可以使用JavaScript来做到这一点:
var count = 4;
function anim() {
    if (count > 0) {
        console.log(count);
        count--;
        setTimeout(anim, 700);
    }
    else {
        alert('end of counting')
    }
}
anim();

这段代码会从4开始倒数,当计数器归零时执行一个函数。

http://jsfiddle.net/GSWRW/查看运行示例。


2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接