-1

I'm trying to make a countdown timer to go from 15 minutes 0 seconds to 0 minutes 0 seconds but it appears that it doesn't want to display in JsFiddle. Another program is that my date variable isn't actually set to 15 minutes and 0 seconds. How can I fix this?

var date = new Date();
var sec = date.getSeconds();
var min = date.getMinutes();
var handler = function() {
  sec--;
  if (sec == 60) {
    sec = 0;
    min--;
    else if (sec < 0) {
      date.setSeconds(0);
    } else if (min < 0) {
      date.setMinutes(0);
    }
  }
  document.getElementById("time").innerHTML = (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec);
};
handler();
setInterval(handler, 1000);
<b>Offer Ends In:</b>
<h1 id="time" style="text-align: center"></h1>
Wizard7611
  • 35
  • 1
  • 4
  • Tip: If it doesn't run in jsFiddle, it is unlikely to run anywhere. Your if statement inside your function is structured incorrectly, you need to fix it or it will break the entire script. – Simon Hyll May 01 '17 at 01:59

4 Answers4

1

Well, for one thing, you don't have a closing brace before the else, so it won't even run as is.

In addition, I'm not sure why you need to fiddle around with date objects for a countdown timer, since the current date/time is irrelevant.

You should start with something like:

function pad2(s) {
    return ("00" + s).slice(-2);
}

var handler = function() {
    if (--sec < 0) {
        sec = 59;
        if (--min < 0) {
            min = 0;
            sec = 0;
        }
    }
    document.getElementById("time").innerHTML = pad2(min) + ":" + pad2(sec);
};

var sec = 1;
var min = 15;
handler();
setInterval(handler, 1000);

You'll notice I've refactored out the padding code since it's "questionable" whether you should ever violate the DRY principle. You certainly shouldn't violate it twice on a single line :-)


In terms of testing, you can create a simple static page which runs the timer as follows.

I've also reduced starting time to a little over ten minutes and accelerated time ten-fold so you don't have to wait around for a full quarter hour to test the whole thing (it should take a smidgen more than a minute to complete).

<html>
  <body>
    <b>Offer Ends In:</b>
    <h1 id="time" style="text-align: left"></h1>

    <script type="text/javascript">
      function pad2(s) {
          return ("00" + s).slice(-2);
      }

      var handler = function() {
          if (--sec < 0) {
              sec = 59;
              if (--min < 0) {
                  min = sec = 0;
              }
          }
          document.getElementById("time").innerHTML = pad2(min) + ":" + pad2(sec);
      };

      var sec = 6;
      var min = 10;
      handler();
      setInterval(handler, 100); // 10x normal speed, use 1000 for reality
    </script>
  </body>
</html>
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Thank you. How can I add the finalized JsFiddle's HTML and Javascript code to my website for it to actually work? – Wizard7611 May 01 '17 at 03:03
  • @Wizard7611, that's a whole *different* question and depends a great deal on what is actually running on your target website. I'll add a static page that gives you what you need in simplest form. – paxdiablo May 01 '17 at 03:11
0

For starters, you do not have a closing brace before the else if and you need to remove the brace before your document.getElementById

Jerhemy
  • 560
  • 4
  • 12
  • While this may be a correct comment, and helpful, on SO "answers" are meant for only complete resolutions to the original post.... also, there are some posts that aren't meant to be answered (like, when it's a simple typographical error) - Thanks for the contribution! Please expand your answer or check out the [help section](http://stackoverflow.com/help) if need be. – wahwahwah May 01 '17 at 02:18
0

1) Closed your curly-bracket for your if condition.

2) Your code failed to load properly because your JavaScript loads before the page recognizes the time DIV element. Since you didn't use an event listener for the page loading first, I added that... and it seems to be working.

3) Important note... The timer logic needs a lot of work... You're better off using a time DIFF statement otherwise you've got about 200-300 lines more to write just on calculating seconds, minutes, hours, days etc.

Looking at the page as it stands has this... 15:0-289

** Update ** adding the padding technique rectified the above note...

Here's a solution for that. Check time difference in Javascript

<html>
    <head>

        <script type="text/javascript">
            var date = new Date();
            var sec = date.getSeconds();
            var min = date.getMinutes();
            document.addEventListener("DOMContentLoaded", function(event) { 
                var myTimer = setInterval(handler, 1000);
            });

            function pad2(s) {
                return ("00" + s).slice(-2);
            }

            var handler = function() {
                if (--sec < 0) {
                    sec = 59;
                    if (--min < 0) {
                        min = 0;
                        sec = 0;
                    }
                }
                document.getElementById("time").innerHTML = pad2(min) + ":" + pad2(sec);
            };
        </script>
    </head>

    <body>
        <b>Offer Ends In:</b>
        <h1 id="time" style="text-align: center"></h1>
    </body>
</html>
Community
  • 1
  • 1
Steve Kline
  • 805
  • 4
  • 11
  • You might have had this code following the in-line H1 element... if so... nvm my edit on the listener event. :) – Steve Kline May 01 '17 at 02:25
-1

I just made this StopWatch. You can use it without a button and it will work like you want.

//<![CDATA[
/* external.js */
var doc, bod, htm, C, E, T, MillisecondConverter, StopWatch; // for use on other loads
addEventListener('load', function(){

var doc = document, bod = doc.body, htm = doc.documentElement;
C = function(tag){
  return doc.createElement(tag);
}
E = function(id){
  return doc.getElementById(id);
}
T = function(tag){
  return doc.getElementsByTagName(tag);
}
MillisecondConverter = function(milliseconds, displayMilliseconds){
  var ms = milliseconds, rh = ms/3600000, hp = Math.pow(10, rh.toString().length-2);
  this.hours = Math.floor(rh);
  var rm = (rh*hp-this.hours*hp)/hp*60, mp = Math.pow(10, rm.toString().length-2);
  this.minutes = Math.floor(rm);
  var rs = (rm*mp-this.minutes*mp)/mp*60, sp = Math.pow(10, rs.toString().length-2);
  if(displayMilliseconds){
    this.seconds = Math.floor(rs);
    this.milliseconds = Math.round((rs*sp-this.seconds*sp)/sp*1000);
  }
  else{
    this.seconds = Math.round(rs);
  }
  this.convert = function(){
    return this.hours.toString().replace(/^([0-9])$/, '0$1')+'&#058;'+this.minutes.toString().replace(/^([0-9])$/, '0$1')+'&#058;'+this.seconds.toString().replace(/^([0-9])$/, '0$1');
  }
}
StopWatch = function(displayNode, millisecondInterval){
  this.hours = this.minutes = this.seconds = this.milliseconds = 0;
  this.millisecondInterval = millisecondInterval || 1000;
  this.displayNode = displayNode; this.began = false; this.paused = false;
  var t = this, ms, iv, fi;
  this.begin = function(doneFunc, context){
    var c = context || this;
    ms = this.hours*3600000+this.minutes*60000+this.seconds*1000+this.milliseconds;
    var mc = new MillisecondConverter(ms), dn = this.displayNode, cv = mc.convert();
    if(dn.innerHTML || dn.innerHTML === ''){
      dn.innerHTML = cv;
    }
    else{
      dn.value = cv;
    }
    this.began = true;
    fi = function(mi){
      var nd = new Date, bt = nd.getTime(), ii = t.millisecondInterval;
      ms = mi;
      iv = setInterval(function(){
        var nd = new Date, ct = nd.getTime(), tl = ct-bt;   
        var mc = new MillisecondConverter(mi-tl), dn = t.displayNode;
        if(tl >= mi){
          clearInterval(iv); doneFunc.call(c); cv = '00&#058;00&#058;00';
          if(dn.innerHTML || dn.innerHTML === ''){
            dn.innerHTML = cv;
          }
          else{
            dn.value = cv;
          } 
          t.began = false;
          return;
        }
        cv = mc.convert(); ms -= ii;
        if(dn.innerHTML || dn.innerHTML === ''){
          dn.innerHTML = cv;
        }
        else{
          dn.value = cv;
        }
      }, ii);
    }
    fi(ms);
  }
  this.pause = function(){
    clearInterval(iv); iv = undefined; this.paused = true;
    return this;
  }
  this.resume = function(){
    fi(ms); this.paused = false;
    return this;
  }
}
var cd = new StopWatch(E('remain')), out = E('out');
cd.seconds = 30;
E('btn').addEventListener('click', function(){
  if(!cd.began){
    out.innerHTML = '';
    cd.begin(function(){
      out.innerHTML = 'Countdown Complete';
    });
  }
  else{
    cd.paused ? cd.resume() : cd.pause();
  }
});

});
//]]>
/* external.css */
html,body{
  padding:0; margin:0;
}
.main{
  width:980px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <title>StopWatch</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div class='main'>
    <div id='remain'>00&#058;00&#058;30</div>
    <input id='btn' type='button' value='StopWatch' />
    <div id='out'></div>
  </div>
</body>
</html>
StackSlave
  • 10,613
  • 2
  • 18
  • 35