simple 3-2-1 countdown in javascript/jquery

vee picture vee · Apr 9, 2011 · Viewed 11k times · Source

i'm trying to create a simple 3-2-1 counter. i would like to display the 3, 2, and 1, as well as run a function at the end of the countdown. i've tried a couple things to no avail:

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

and:

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

in these cases, it does get to 2 but never to 1. i also installed the doTimeout plugin (http://benalman.com/projects/jquery-dotimeout-plugin/) and tried this:

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

and:

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

what am i doing wrong? thanks.

Answer

EMMERICH picture EMMERICH · Apr 9, 2011
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);

Doesn't use jQuery as much, but should work fine.