Countdown Counter Javascript or Jquery?

冷暖自知 提交于 2019-12-11 15:47:07

问题


I am tryin to create a simple counter that counts backwards from 3 to 0 or 5 to 0 or whatever.

It's a timer for a questions so each number needs to be visible to the user.

I tried:

for (i=3;i>=0;i--){

   $(".timerInner").delay(500).text( i );

}

But had no luck.


回答1:


Try this,

var i =5;

var timer = setInterval( calltimer, 500);

function calltimer(){
    $(".timerInner").append( i );

    if(i == 0){
       clearInterval(timer);
    }
    i--;

}



回答2:


Use setInterval/clearInterval instead:

var i = 5;

var t = setInterval(function() {
    i === 0 && clearInterval(t);

    $(".timerInner").text(i);
    i--;
}, 1000);​



回答3:


I recommend to use JavaScript method setTimeout:

function countdown(remainingTime) {
    $('.timerInner').text(remainingTime);
    if (remainingTime > 0)
        setTimeout(function() { countdown(remainingTime - 100); }, 100);
}

​countdown(1000);​

Fiddle example to play with: http://jsfiddle.net/MSa8h/1/




回答4:


uou need to create a loop bassed on setTimeout function, here's a sketch

var i = 3;

var calc = function(){
    i--;
    if(i==0){
      //start new iteration
      timeout();
    }else{
      //end loop
      return;
    }

};

var timeout = function(){
    setTimeout(calc,1000);
};



回答5:


var i =5;

var timer = setInterval( calltimer, 500);

function calltimer(){
   $(".timerInner").text( i );

 if(i == 0){
    clearInterval(timer);
 }
 i--;

}

Thanks for the help



来源:https://stackoverflow.com/questions/9546389/countdown-counter-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!