Amy Neville
Amy Neville

Reputation: 10581

Javascript seconds countdown

I have been trying for hours to make a javascript function that will take an input time in seconds and provide a countdown. For some reason it just refuses to count down after the first second and I can't figure out why not.

Here is my HTML:

<span style="display:none;" id="unixtime_coming_0">600</span><span onload='timer()' id="timer_coming_0"></span>

And here is my javascript:

setInterval(function timer() {
  var count = document.getElementById("unixtime_coming_0").innerHTML;
  count = count - 1;
  if (count <= 0) {
    clearInterval(counter);
    return;
  }
  var days = Math.floor(count / 86400);
  var hours = Math.floor(count / 3600) % 24;
  var minutes = Math.floor(count / 60) % 60;
  var seconds = count % 60;
  document.getElementById("timer_coming_0").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; // watch for spelling
}, 1000);

Upvotes: 1

Views: 3530

Answers (3)

vdua
vdua

Reputation: 1331

For accurate count down you need to use new Date().getTime(). Please have a look at this answer for a similar question https://stackoverflow.com/a/15635372/1523245

Upvotes: 0

Blender
Blender

Reputation: 298106

Defining a named function doesn't return anything. You have to define it outside of setInterval:

var counter = setInterval(timer, 1000);

function timer() {
    var unixtime = document.getElementById("unixtime_coming_0");
    var count = parseInt(unixtime.innerHTML, 10);
    unixtime.innerHTML = count - 1;

    if (count < 1) {
        clearInterval(counter);
        return;
    }

    var days = Math.floor(count / 86400);
    var hours = Math.floor(count / 3600) % 24;
    var minutes = Math.floor(count / 60) % 60;
    var seconds = count % 60;

    document.getElementById("timer_coming_0").innerHTML= days + "d " + hours + "h " + minutes + "m " + seconds + "s"; // watch for spelling
}

I'd get rid of the setInterval completely. Just call timer via setTimeout inside of timer itself.

Upvotes: 2

user2230607
user2230607

Reputation: 21

count is being reset to 600 on every loop. Just move its declaration outside of the function, like so:

var count = parseInt(document.getElementById("unixtime_coming_0").innerHTML, 10);
setInterval(function timer() {
    count = count - 1;
[...]

Upvotes: 0

Related Questions