Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    New to the CF scene
    Join Date
    Dec 2017
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Need Help with Simple Timer

    I'm trying to put a counter on our website that will start with an initial number, say 25,000 and count up by one every 20 minutes (adjustable to every 10-30 minutes), so it will just keep counting up day by day. I asked a developer to give it a try based on using current date and time, subtracting an aribitrary prior date and time to give us days/time since the starting point, and then use a little math to convert that into "counts" that represent an interval of 20 minutes or whatever we want. He came up with some code as follows, that I'm sure doesn't work this way and I don't understand quite what it is doing, though it does count up, but is not adjustable.

    function served(){
    var decrease_increase=25000

    var counterdate=new Date()
    var currenthits=counterdate.getTime().toString()
    currenthits=parseInt(currenthits.substring(4,currenthits.length-6))+decrease_increase
    document.write(currenthits);
    }
    served()

    and there is another line in the code that outputs to a display.

    Can anyone offer suggestions on how to build the counter the way I need. I think the logic behind it is get the current date and time, turn it into an integer, subtract some integer representing a prior known date and time, use that difference to understand the length of time, then manipulate with division or other math operations to turn it into something that represents different time intervals (eg for one count over 20 minutes, 3 per hour, 72 per day etc).

    Any help?

    thanks much

    Jeff

  2. #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    19,486
    Thanks
    218
    Thanked 2,703 Times in 2,679 Posts
    Could you explain further what you mean by "adjustable"? Adjustable by the user? Or adjustable by the programmer? It would help if you gave us a clearer idea of the purpose of your code. Any change to the counter will be visible only to that user, and will be carried over to another session only if your use a cookie or webStorage.

    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.

  3. Users who have thanked Philip M for this post:

    jeffamm (12-07-2017)

  4. #3
    Senior Coder deathshadow's Avatar
    Join Date
    Feb 2016
    Location
    Keene, NH
    Posts
    2,468
    Thanks
    2
    Thanked 361 Times in 351 Posts
    As @Phillp M said, we need more information on what this number is, who/why it is updating, who can see it (is this applied to ALL users or just the current one, just the current session? current page-load?)

    But more than that, if your "programmer" is using document.write, FIND ANOTHER PROGRAMMER!
    I would rather have questions that can't be answered, than answers that can't be questioned.
    http://www.cutcodedown.com

  5. Users who have thanked deathshadow for this post:

    jeffamm (12-07-2017)

  6. #4
    New to the CF scene
    Join Date
    Dec 2017
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Hi, thanks for the replies. The counter will reflect the number of dog-walks we've delivered for customers since we opened, based on our average rate, since the business opened 4 years ago. So it should start with our known number and right now we do about 80 dog-walks per day, so the number should increase by that number over the course of every day, so go up by one roughly every 20 minutes. There is nothing on the site or other system to use to reflect actual walks so we just need to base it on our daily average, and adjust it from time to time to reflect reality. I don't want to use a cookie as that suggests it would be different for each session and that isn't the case. The number displayed should be the same for all visitors at a given time, and just increase at the adjustable daily rate, preferably by one at a time. The adjustment is done by us, in the code, not by the site visitor.

    Yes I understand the comment about document.write which the W3 tutorial site said should be used only for testing.

    From searching around I found the code below which I think is pretty close to what I need but not sure how to tailor it. thanks folks!

    var startDateTime = new Date(2014,8,26,2,1,0,0); // YYYY (M-1) D H m s (start time and date from DB)
    var startStamp = startDateTime.getTime();

    var newDate = new Date();
    var newStamp = newDate.getTime();

    var timer;

    function updateClock() {
    newDate = new Date();
    newStamp = newDate.getTime();
    var diff = Math.round((newStamp-startStamp)/1000);

    var d = Math.floor(diff/(24*60*60));
    diff = diff-(d*24*60*60);
    var h = Math.floor(diff/(60*60));
    diff = diff-(h*60*60);
    var m = Math.floor(diff/(60));
    diff = diff-(m*60);
    var s = diff;

    document.getElementById("time-elapsed").innerHTML = d+" day(s), "+h+" hour(s), "+m+" minute(s), "+s+" second(s) working";
    }

    setInterval(updateClock, 1000);

  7. #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    19,486
    Thanks
    218
    Thanked 2,703 Times in 2,679 Posts
    As I see it you are requiring a counter which (starting from a given start value and start date adds 1 to the counter every 20 minutes (3 per hour).

    This would appear to meet your needs:-


    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    
    <script type="text/javascript">
    
    var startValue = 25000;
    var startDay = new Date(2017,0,1,0,0,0); //  January 1 2017 - change to suit (note that months in Javascript are 0-11)
    
    function ProcessCounter() {
    
    var now = new Date();
    var numSecs = Math.ceil(((now.getTime() - startDay.getTime())/1000));
    var numMins = numSecs/60
    var num20Mins = numMins/20; // number of 20 minute intervals
    var count = parseInt(startValue + num20Mins);  // add one per 20 minutes
    document.getElementById("result").innerHTML = count;
    
    }
    
    
    function addCommas(nStr) {
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
    nStr = nStr.replace(rgx, '$1' + ',' + '$2');
    }
    return nStr;
    }
    
    </script> 
    
    </head>
    
    <body onload = "ProcessCounter()"> 
    <span id = "result"></span>
    
    </body>
    </html>
    The fans are heading home with their heads firmly between their tails. - Commentator Sky Sports
    Last edited by Philip M; 12-07-2017 at 09:04 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.

  8. Users who have thanked Philip M for this post:

    jeffamm (12-07-2017)

  9. #6
    New to the CF scene
    Join Date
    Dec 2017
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Wow! Thank you Philip! How do I send you a pint?

  10. #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    19,486
    Thanks
    218
    Thanked 2,703 Times in 2,679 Posts
    Sorry, I seem to have left a couple of lines out of the above code (to add commas to the resultant number). This is of course optional.

    Code:
    var count = parseInt(startValue + num20Mins);  // add one per 20 minutes
    count = count.toString();
    count = addCommas(count);
    document.getElementById("result").innerHTML = count;

    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.

  11. #8
    Senior Coder deathshadow's Avatar
    Join Date
    Feb 2016
    Location
    Keene, NH
    Posts
    2,468
    Thanks
    2
    Thanked 361 Times in 351 Posts
    That could actually be simplified WAY down...

    Code:
    <!DOCTYPE HTML><html><head>
    <title>Counter Demo</title>
    </head><body> 
    
    <span id="counter"></span>
    
    <script>
    
    var
    	counter = 25000,
    	interval = 1200000; /* 20 minutes */
    	
    counter += Math.floor((
    	new Date().getTime() - new Date(2017,0,1,0,0,0).getTime()
    ) / interval);
    document.getElementById('counter').appendChild(
    	document.createTextNode(counter.toLocaleString())
    );
    
    </script> 
    
    </body></html>
    If you put the script before </body> after the span, you don't need that outdated outmoded onload nonsense, this is 2017 not 2007 you don't have to say type="text/JavaScript" anymore, you went overboard on relatively simple math, and you've got some funny regex function to do something that's been built into JavaScript since... well, toLocalString works on Number even in IE5.

    For laughs, how about we make it so that it updates on the 20 minute every 20 minutes should someone leave the page open that long?

    Code:
    <!DOCTYPE HTML><html><head>
    <title>Counter Demo</title>
    </head><body> 
    
    <span id="counter"></span>
    
    <script>
    
    var
    	counter = 25000,
    	interval = 1200000, /* 20 minutes */
    	counterSpan = document.getElementById('counter'),
    	startTime = new Date().getTime();
    	
    function counterShow() {
    	while (counterSpan.firstChild) counterSpan.removeChild(counterSpan.firstChild);
    	counterSpan.appendChild(document.createTextNode(counter.toLocaleString()));
    }
    	
    function counterCallback() {
    	counter++;
    	counterShow();
    	setTimeout(counterCallback, interval);
    }
    
    counter += Math.floor((startTime - new Date(2017,0,1,0,0,0).getTime()) / interval);
    counterShow();
    
    var temp = setTimeout(
    	counterCallback, 
    	(Math.floor(startTime / interval) + 1) * interval - startTime
    );
    	
    </script> 
    
    </body></html>
    So if you leave the page open, on the hour, 20 past, and 20 of -- it will increment the counter.

    Note, I'm using the DOM not innerHTML so it doesn't trigger the browser's parser. That is the PREFERRED way of putting content in an element.
    Last edited by deathshadow; 12-08-2017 at 10:31 AM.
    I would rather have questions that can't be answered, than answers that can't be questioned.
    http://www.cutcodedown.com

  12. #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    19,486
    Thanks
    218
    Thanked 2,703 Times in 2,679 Posts
    You are perfectly right, but when responding to requests I often use code which is more verbose than strictly necessary, so as to help the questioner understand it better. I don't think it makes any practical difference - I take the view that if it works as intended then a few bytes more or less does not make any difference. Your remarks about innerHTML are perfectly valid, but in the real world innerHTML is entirely OK in a simple situation such as this.

    As I understand it Number().toLocaleString() has a different format in different browsers, so I prefer my regex. Perhaps the issue has been solved by now.

    Personally I would not use the same name "counter" for a span id and also a script variable.
    Last edited by Philip M; 12-08-2017 at 08:28 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.

  13. #10
    New to the CF scene
    Join Date
    Dec 2017
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts
    So I've tried all of the suggested code and they all work great in a stand-alone file but I don't quite see how to get the results into my existing code which displays a counter on the website. The existing code is

    <span class="s-name" style="font-size:12px;">
    <span id="test">
    <script>
    function served(){
    var decrease_increase=63000

    var counterdate=new Date()
    var currenthits=counterdate.getTime().toString()
    currenthits=parseInt(currenthits.substring(4,currenthits.length-6))+decrease_increase
    document.write(currenthits);
    }
    served()
    </script></span></span>

    I know the document.write is not a good idea but it is working. How do I adapt the suggested code to show in my currently coded display? thanks again

  14. #11
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    19,486
    Thanks
    218
    Thanked 2,703 Times in 2,679 Posts
    The code(s) we have supplied are supposed to substitute for (replace) your existing code.

    </script></span></span> is quite wrong. Do not mix up HTML and Javascript. You first span has no id so it cannot be accessed.
    Last edited by Philip M; 12-09-2017 at 05:02 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.


 

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
  •