0

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.

2
  • 1
    First, the loop is very fast, so all these three statements in the loop body are basically executed at the same time. Second, text is not an animation function, so calling delay first has no effect. I think there a million countdown scripts for jQuery you can use. Commented Mar 3, 2012 at 13:14
  • Please choose a best answer @Splatty Commented Mar 4, 2012 at 14:35

5 Answers 5

3

Use setInterval/clearInterval instead:

var i = 5;

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

    $(".timerInner").text(i);
    i--;
}, 1000);​
Sign up to request clarification or add additional context in comments.

Comments

2

Try this,

var i =5;

var timer = setInterval( calltimer, 500);

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

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

}

1 Comment

Thanks I ended up using this code, but the .append(i) I swithced with .text(i) append did not seem to show results..
1

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/

Comments

0

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

1 Comment

You can also omit the else block.
0
var i =5;

var timer = setInterval( calltimer, 500);

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

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

}

Thanks for the help

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.