www.webdeveloper.com
Results 1 to 7 of 7

Thread: Help me fix up my countdown timer!

  1. #1
    Join Date
    Dec 2013
    Posts
    4

    Question Help me fix up my countdown timer!

    Hi

    Im making a Countdown Timer for a website and need it to support as many browsers as possible. Currently it does not have a very broad support.

    I have read that the dataset element is not the best way to go for maximal browser support (there is probably a lot of other code that is not very good for wide browser support, however i am not experienced enough to find another way to achieve this effect). Here is my code:

    Code:
    var target_date = new Date("Feb 24, 2014 20:00:00").getTime();
    
    var Clock = (function(){  
      var exports = function(element) {
        this._element = element;
        var html = '';
        for (var i=0;i<6;i++) {
          html += '<span>&nbsp;</span>';
        }
        this._element.innerHTML = html;
        this._slots = this._element.getElementsByTagName('span');
        this._tick();
      };
      exports.prototype = {
        _tick:function() {
          var time = new Date().getTime();
          var seconds_left = (target_date - time) / 1000;
          // do some time calculations
          var days = parseInt(seconds_left / 86400);
          seconds_left = seconds_left % 86400;
    
          var hours = parseInt(seconds_left / 3600);
          seconds_left = seconds_left % 3600;
    
          var minutes = parseInt(seconds_left / 60);
          this._update(this._pad(days) + this._pad(hours) + this._pad(minutes));
          var self = this;
          setTimeout(function(){
            self._tick();
          },1000);
        },
        _pad:function(value) {
          return ('0' + value).slice(-2);
        },
        _update:function(timeString) {
          var i=0,l=this._slots.length,value,slot,now;
          for (;i<l;i++) {
            value = timeString.charAt(i);
            slot = this._slots[i];
            now = slot.dataset.now;
            if (!now) {
              slot.dataset.now = value;
              slot.dataset.old = value;
              continue;
            }
            if (now !== value) {
              this._flip(slot,value);
            }
          }
        },
        _flip:function(slot,value) {
          slot.classList.remove('flip');
          slot.dataset.old = slot.dataset.now;
          slot.dataset.now = value;
          slot.offsetLeft;
          slot.classList.add('flip');
        }
      };
      return exports;
    }());
    var i=0,clocks = document.querySelectorAll('.clock'),l=clocks.length;
    for (;i<l;i++) {
      new Clock(clocks[i]);
    }
    You can see the timer over at codepen: http://codepen.io/olka/pen/dreaL

    So how can I make this work in most modern browsers?

    I am very grateful for all the help I can get!

  2. #2
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773
    Instead of using the dataset property on DOM nodes, use the setAttribute() method and data-* HTML 5 attributes:

    slot.setAttribute("data-old", slot.getAttribute("data-now"));
    slot.setAttribute("data-now", value);

    The dataset property is a Hash of all data-* HTML 5 attributes, such that:

    HTML Code:
    <div data-post-id="1" data-post-title="Test"></div>
    Becomes:

    Code:
    // assume the div variable is a DOM node reference to the <div> above
    
    div.dataset.postId // Equals "1"
    div.dataset.postTitle // Equals "Test"

  3. #3
    Join Date
    Dec 2013
    Posts
    4
    Thanks! That actually helped a lot! I have a made a new version with the changes here: http://codepen.io/olka/pen/lLFDa

    If there is more you see that I should change in order to make the code better, please let me know. I am still learning!

  4. #4
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,223
    DON'T use SetTimeout, use setInterval to call your update functions, you don't need to parseInt a value that is already a number.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  5. #5
    Join Date
    Dec 2013
    Posts
    4
    What are the benefits of using setInterval over setTimeout?

  6. #6
    Join Date
    Dec 2013
    Posts
    4
    Actually in this case parseInt is necessary for the timer to work properly. Also, I think its correct to use setTimeout if I want to trigger the code once after a set interval. setInterval triggers the code multiple times and I only want to trigger it once. Am I right or did I misunderstand?

  7. #7
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,223
    setInterval once set will occur at 'nth' milliseconds that you set it for.

    setTimeout will only occur after 'nth' milliseconds occurs and the time between end and recreation of the interval next adds 'nth' millisconds to the function call.

    An event is created and you have a small time 'nth' milliseconds for it to create, so you could have 250 milliseconds added to a 1000 millisecond event trigger using setTime out. It is not necessarily your computer that will have a problem but older PC's that people may have that are the consideration.

    You have to remember that some people can't afford new PC's and inherit hand me downs or managed to gather the parts to make a PC and these older architectures make up the majority of user machines. My first PC was such a machine, my second was a self build out of a mixed bag of new and second hand parts, my third and forth PC's were hand me downs, my fifth PC was another home brew kit of spares I had amassed and a board that someone chucked out that only problem with it was the CPU wasn't properly inserted!!! My sixth PC was a barebones system that I bought new and bought new parts for it.

    In CPU terms, started with Intel 8086 @ 113Mhz, then AMD 650Mhz, and then made it past the 1Ghz mark with an Intel1.3Ghz, then I leapt up to an Intel3.1Ghz

    What this means is that the architecture has grown fast enough for those users who have them, will support a browser that interprets the script to then react fast enough, the amount of interpreter lag that gets introduced gets larger the slower the system.

    So what happens? You could very well have users of the countdown seeing your count down witnessing jumps of 2 and 3 second intervals, depending on how fast the machine is and when the next cycle is triggered.

    SetInterval overcomes allot of these problems as it is an interval that has been initiated and will call the desired function at that aet interval, you only have one element of lag and that is in the functions initialization to start with, thereafter you have no lag.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles