Web Analytics Made Easy -
StatCounter Javascript timer problem - CodingForum

Announcement

Collapse
No announcement yet.

Javascript timer problem

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Javascript timer problem

    Hey everyone!

    I got some code and would much appreciate if you could help me with it. It's a countdown timer and it currently works at 24 hour intervals and resets after each interval. It shows everyone the same countdown to EST midnight, so that the countdown is the same for everyone regardless of where they visit from. Obviously this has no server side scripting, and is dependent of the accuracy of the end users computer clock, but it's good enough for me.

    What I'm trying to do is to get the countdown to work at 6 hour intervals, I have it working at 12 hour intervals by changing a few things.

    Here's the countdown to EST midnight code:
    https://jsfiddle.net/o13xta1v/

    Javascript
    Code:
    function getSeconds() {
    var now = new Date();
    var requiredTimeZone = 240;
    var time = now.getTime() + (now.getTimezoneOffset() * 60000) - (requiredTimeZone * 60000);;
    var midnight = new Date(now.getUTCFullYear(),now.getUTCMonth(),now.getUTCDate(),0,0,0);
    var ft = midnight.getTime() + 86400000;
    var diff = ft - time;  
    diff = parseInt(diff/1000);
    if (diff > 86400) {diff = diff - 86400}
    startTimer (diff);
    }
    
    
    var timeInSecs;
    var ticker;
    
    function startTimer(secs){
    timeInSecs = parseInt(secs);
    ticker = setInterval("tick()",1000); 
    tick();
    }
    
    function tick() {
    var secs = timeInSecs;
    if (secs>0) {
    timeInSecs--;
    }
    else {
    clearInterval(ticker);
    }
    
    var hours= Math.floor(secs/3600);
    secs %= 3600;
    var mins = Math.floor(secs/60);
    secs %= 60;
    var result = ((hours < 10 ) ? "0" : "" ) + hours + ":" + ( (mins < 10) ? "0" : "" ) + mins
                      + ":" + ( (secs < 10) ? "0" : "" ) + secs;
    document.getElementById("countdown").innerHTML = "Countdown: " + result;
    }
    HTML
    Code:
    <body onload = "getSeconds()">
    
    <span id="countdown" style="font-weight: bold;"></span>
    I got the timer working in 12 hour intervals by changing the var ft from 86400000 to 43200000 and the diff from 86400 to 43200. I tested it and it worked fine, I even tried simulating the timer going past the first reset interval by changing the requiredTimeZone to different times, and the countdown was showing correctly:
    https://jsfiddle.net/o13xta1v/1/

    Then I thought that by changing the var ft from 43200000 to 21600000 and the diff from 43200 to 21600 the timer interval would be 6 hours, but now it doesn't work anymore, instead it shows something like: "0-5:0-4:0-10" and isn't counting down any more.

    Here are the changes I made (not working):
    https://jsfiddle.net/o13xta1v/2/

    Javascript
    Code:
    function getSeconds() {
    var now = new Date();
    var requiredTimeZone = 240;
    var time = now.getTime() + (now.getTimezoneOffset() * 60000) - (requiredTimeZone * 60000);;
    var midnight = new Date(now.getUTCFullYear(),now.getUTCMonth(),now.getUTCDate(),0,0,0);
    var ft = midnight.getTime() + 21600000;
    var diff = ft - time;  
    diff = parseInt(diff/1000);
    if (diff > 21600) {diff = diff - 21600}
    startTimer (diff);
    }
    
    
    var timeInSecs;
    var ticker;
    
    function startTimer(secs){
    timeInSecs = parseInt(secs);
    ticker = setInterval("tick()",1000); 
    tick();
    }
    
    function tick() {
    var secs = timeInSecs;
    if (secs>0) {
    timeInSecs--;
    }
    else {
    clearInterval(ticker);
    }
    
    var hours= Math.floor(secs/3600);
    secs %= 3600;
    var mins = Math.floor(secs/60);
    secs %= 60;
    var result = ((hours < 10 ) ? "0" : "" ) + hours + ":" + ( (mins < 10) ? "0" : "" ) + mins
                      + ":" + ( (secs < 10) ? "0" : "" ) + secs;
    document.getElementById("countdown").innerHTML = "Countdown: " + result;
    }
    Please help me! Thanks in advance!

  • #2
    Gotta post a quick update. I was messing around with the code and it seems that the 12 our interval isn't actually working correctly either. Seems to have something to do with the requiredTimeZone.. Does the same thing with the 12 hour interval as it does with the 6 hour interval. When it gets past a certain time, it breaks down. 24 hour midnight interval seems to work fine though.

    Maybe I need to use something other than midnight.getTime?

    Comment


    • #3
      I had the same problem testing your original code for the 12 hour interval.

      Might consider countdowns to the closest 6 hr interval to 18:00, 12:00, 6:00 and 0:00 (military times)
      as alternative logic.

      Comment


      • #4
        A big problem with time zones is Daylight Saving Time, which is not consistent.

        You might have a look at
        Convert the local time to another time zone with this JavaScript - TechRepublic

        The following code may help you, but is of course GMT based. You might find it simpler to change the times to EST.

        Code:
        <!DOCTYPE HTML>
        <html>
        <head>
        </head>
        
        <body onload = "getSeconds()">
        
        Assume updates are at six-hour intervals, 0000, 0600, 1200, 1800<br><br>
        
        <span id="countdown" style="font-weight: bold;"></span>
        <script type = "text/javascript">
        
        function getSeconds() {
        var now = new Date();
        var hh = now.getHours();
        var mn = now.getMinutes();
        var ss = now.getSeconds();
        var secsToNow = (hh * 3600) + (mn * 60) + ss;  
        secsToGo = 86400 - secsToNow;  // remaining seconds in day
        secsToGo = secsToGo%21600;    // next 6 hours interval
        
        //secsToGo = secsToGo%21600-10800;    // next 6 hours interval, but adjust times -3 hours to (say) 2100 (then 0300, 0900, 1500)
        //if (secsToGo < 0) {secsToGo = secsToGo + 21600}
        
        startTimer(secsToGo);
        }
        
        var timeInSecs;
        var ticker;
        
        function startTimer(secs){
        timeInSecs = parseInt(secs);
        ticker = setInterval("tick()",1000); 
        tick(); // to start counter display right away
        }
        
        function tick() {
        var secs = timeInSecs;
        if (secs>0) {
        timeInSecs--;
        }
        else {
        clearInterval(ticker); // stop counting at zero
        //getSeconds();  // and start again if required
        }
        
        var hours= Math.floor(secs/3600);
        secs %= 3600;
        var mins = Math.floor(secs/60);
        secs %= 60;
        var result = "The next update will be in " +  hours + " hours " + ( (mins < 10) ? "0" : "" ) + mins
                          + " minutes " + ( (secs < 10) ? "0" : "" ) + secs + " seconds";
        document.getElementById("countdown").innerHTML = result;
        }
        
        </script>
        
        <span id="countdown" style="font-weight: bold;"></span>
        
        </body>
        </html>
        Last edited by Philip M; Sep 25, 2016, 02:05 PM.

        All the code given in this post has been tested and is intended to address the question asked.
        Unless stated otherwise it is not just a demonstration.

        Comment


        • #5
          Try replacing this:
          Code:
          if (diff > 86400) {diff = diff - 86400}
          by this:
          Code:
          diff = diff % 21600;

          Comment


          • #6
            Originally posted by Philip M View Post
            A big problem with time zones is Daylight Saving Time, which is not consistent.

            You might have a look at
            Convert the local time to another time zone with this JavaScript - TechRepublic

            The following code may help you, but is of course GMT based. You might find it simpler to change the times to EST.
            Thanks for the reply Philip! I find your solution very good and I plan on using it.

            I'm almost a complete newbie when it comes to Javascript and coding in general, and although that article did give me some ideas, I ran into a dead end..

            So I started off by using now.getUTCHours/Minutes/Seconds instead of now.getHours/Minutes/Seconds.

            Here's the fiddle:
            https://jsfiddle.net/o13xta1v/4/

            Next I tried to offset the time to get it to EST, which would be -5 from UTC. I feel like this could be a simple and nice solution to it, but cannot find a way to implement it. I tried using now.getTimezoneOffset() but I'm unable to make any changes to the time.

            Any input would be much appreciated.

            Comment


            • #7
              Also big thanks to jmrker and Sempervivum for input!

              Comment


              • #8
                Originally posted by cluelessnoob View Post
                I tried using now.getTimezoneOffset() but I'm unable to make any changes to the time.
                getTimezoneOffset() gives the timezone difference between the local computer and UTC. You don't need it if you use UTC time.

                If you are looking at counting down to 0,6,12 and 18 hours for timezone -5 then that will be 5,11,17 and 23 UTC so just select the different hours to count down to and stick with UTC and avoid the offset complication.
                Stephen
                Learn Modern JavaScript - http://javascriptexample.net/
                Helping others to solve their computer problem at http://www.felgall.com/

                Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

                Comment


                • #9
                  The last version seems to be faulty: My local time is 09:28, timer says 4 hours 31 min ...
                  Version 3 seems to work fine: Timer says 2 hours 31 min ...
                  DST is active for me, CET (Berlin).

                  Comment


                  • #10
                    The last version of what? My script works correctly.

                    As felgall says, the OP has no need to use getTimeOffset(), but for the record here is how you identify the time in a time zone other than GMT.


                    Code:
                    <script type = "text/javascript">
                    
                    var dt = new Date();  // date and time according to local computer
                    var tzo = dt.getTimezoneOffset();  // the number of minutes offset relative to GMT (UTC)
                    
                    The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. 
                    
                    //tzo = -360;  // for testing GMT-5 = EST
                    
                    tzo = tzo*60*1000;   // minutes to milliseconds
                    var t = dt.getTime();  // expressed in milliseonds
                    var t1 = t+tzo;  // add offset in milliseconds
                    var nd = new Date(t1);  // generate a new date object based on the revised number of milliseconds
                    alert (nd);
                    
                    </script>
                    Last edited by Philip M; Sep 26, 2016, 05:38 AM.

                    All the code given in this post has been tested and is intended to address the question asked.
                    Unless stated otherwise it is not just a demonstration.

                    Comment


                    • #11
                      The last version (4) of the fiddle.

                      Comment


                      • #12
                        Thanks for the replies everyone!

                        Originally posted by Sempervivum View Post
                        The last version seems to be faulty: My local time is 09:28, timer says 4 hours 31 min ...
                        Version 3 seems to work fine: Timer says 2 hours 31 min ...
                        DST is active for me, CET (Berlin).
                        Philip's script indeed works correctly. I only changed the scrip to get UTC times (from ver 3 to ver 4), and then it counts down to UTC, which is 2 hours behind of CET.

                        So when ver 4 was showing you 4 hours ~30 minutes at ~9:30 local time, it was correct, as UTC then was 7:30, and from 7:30 it's 4 hours 30 minutes to 12:00.

                        Ver 3 on the other hand is taking the time from your computer.


                        Originally posted by felgall View Post
                        If you are looking at counting down to 0,6,12 and 18 hours for timezone -5 then that will be 5,11,17 and 23 UTC so just select the different hours to count down to and stick with UTC and avoid the offset complication.
                        Originally posted by Philip M View Post
                        As felgall says, the OP has no need to use getTimeOffset(), but for the record here is how you identify the time in a time zone other than GMT.
                        Thanks to both of you! I ended up using the lines of code that Philip was kind enough to already include earlier:

                        Code:
                        secsToGo = secsToGo%21600-7200;
                        if (secsToGo < 0) {secsToGo = secsToGo + 21600}
                        Fiddle:
                        https://jsfiddle.net/o13xta1v/5/

                        If my logic is correct (a big if), the countdown should now be to EDT times, at 6 hour intervals, 0, 6, 12, 18. At least that's what I'm getting when looking at the EDT time and the countdown, which is a bit weird since -7200 seconds is -2 hours. I'm a bit baffled by the logic here, since EDT is UTC-4, so if anyone has an explanation to that, I'd love to hear it.

                        Comment


                        • #13
                          Actually no need to answer that last question. I just woke up so I'm running a bit slow. It is indeed working correctly now, here's my conclusion:

                          When UTC is 12:00, EDT is 08:00

                          I offset the UTC by -2 hours, meaning that now it's counting down to UTC 10:00, 16:00, 22:00, 04:00

                          Which are in EDT 06:00, 12:00, 18:00, 00:00

                          Big thanks to everyone for helping me out!

                          Comment


                          • #14
                            Originally posted by sampada
                            the problem occurs in this <<if (diff > 86400) {diff = diff - 86400 as >> try to replace this code by diff = diff % 21600;
                            Thanks for the input, but this problem has already been solved, and also, that solution doesn't work. Someone suggested it earlier, and I tried it and it still counts down to midnight. You can try it yourself: https://jsfiddle.net/o13xta1v/

                            Comment

                            Working...
                            X