Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this countdown clock code return an undefined string? [duplicate]

Tags:

javascript

I tried to create a really simple Javascript clock that would countdown to 0 from a time that the user specifies, but for some reason it keeps returning 'undefined' as a string. Here is the source of the clock:

function startTimer(duration) {
  desap = duration - (new Date).getTime() / 1000;
  var timer = desap,
    minutes, seconds;
  setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display = "Ends in " + minutes + " mins and " + seconds + " secs";

    if (--timer < 0) {
      display = "Ended";
    }
    return display;
  }, 1000);
}

document.write(startTimer(999999999999999))

JSFiddle

like image 992
Franco Roura Avatar asked Apr 01 '26 01:04

Franco Roura


1 Answers

Ideally, I would lean toward using the .textContent javascript property, rather than document.write:

var displayTimer = document.getElementsByClassName('display-timer')[0];

function startTimer(duration) {

  setInterval(function() {
    var timer = duration - (new Date).getTime() / 1000;
    var minutes = parseInt(timer / 60, 10)
    var seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    var display = "Ends in " + minutes + " mins and " + seconds + " secs";

    if (--timer < 0) {
      display = "Ended";
    }

    displayTimer.textContent = display;

  }, 1000);
}

window.addEventListener('load',function(){startTimer(999999999999999);},false);
<div class="display-timer">
</div>
like image 75
Rounin - Glory to UKRAINE Avatar answered Apr 02 '26 15:04

Rounin - Glory to UKRAINE