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 に答える