views:

827

answers:

2

I want to use a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. No milliseconds. How can it be coded?

+10  A: 
var count=30;

var counter=setInterval("timer()",1000); //1000 will  run it every 1 second

function timer()
{
  count=count-1;
  if (count <= 0)
  {
     clearInterval(counter);
     //counter ended, do something here
     return;
  }

  //Do code for showing the number of seconds here
}

To make the code for the timer appear in a paragraph (or anywhere else on the page), just put the line:

<span id="timer"></span>

where you want the seconds to appear. Then insert the following line in your timer() function, so it looks like this:

function timer()
{
  count=count-1;
  if (count <= 0)
  {
     clearInterval(counter);
     return;
  }

 docunent.getElementById("timer").innerHTML=count + " secs";
}
Click Upvote
Thanks for the answer. I am having difficulty using it because my timer appears in a paragraph. How can I put the 30, 29, 28, etc. in the middle of a paragraph?
Mike
I edited my answer to show you how to display the timer in the paragraph :)
Click Upvote
In the middle of a paragraph (horizontally) : <p id="timer" style="text-align:center"></p>
Alsciende
Click, your timer will only display "0 secs". You should put the innerHTML update after the decrementation, not in the end case.
Alsciende
Ahh, thanks for catching that. edited and fixed it
Click Upvote
Still not working for me. This paragraph shows up after a period of inactivity by the user. I need a way to call this script inside of the script that waits for the period of inactivity. How can I do that?
Mike
Whereever you want the timer to begin, just put in the code `timer();` to call the timer function
Click Upvote
+3  A: 

I wrote this script some time ago:

Usage:

var myCounter = new Countdown({  
    seconds:5,  // number of seconds to count down
    onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
    onCounterEnd: function(){ alert('counter ended!');} // final action
});

myCounter.start();


function Countdown(options) {
  var timer,
  instance = this,
  seconds = options.seconds || 10,
  updateStatus = options.onUpdateStatus || function () {},
  counterEnd = options.onCounterEnd || function () {};

  function decrementCounter() {
    updateStatus(seconds);
    if (seconds === 0) {
      counterEnd();
      instance.stop();
    }
    seconds--;
  }

  this.start = function () {
    clearInterval(timer);
    timer = 0;
    seconds = options.seconds;
    timer = setInterval(decrementCounter, 1000);
  };

  this.stop = function () {
    clearInterval(timer);
  };
}
CMS