1

I'm a beginner at JS and PHP, so please forgive my ignorance and bear with me :)

I'm trying to implement a live counter on my website. This counter should display the number of translated words up to now, and I'd like this number to update "live" to reflect the number of translated words (based on my yearly average).

To simplify, I set a variable $wordsPerYear with an average of words translated per year, say 1,000. I also set the start date to 10 years ago (2004), so that it returns roughly 10,000.

So here's my code so far:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Live Word Count</title>
    <style type="text/css">
    .count {
        width: 100%;
        margin: 0 auto;
        padding-top: 10%;
        text-align: center;
    }
    </style>
    <?php
    $now = time();
    $start = mktime(0, 0, 0, 1, 01, 2004);
    $wordsPerYear = 1000;
    $totalDays = (($now - $start) / 86400); // number of a seconds in a day
    $count = $totalDays / 365 * $wordsPerYear;
    $count = round($count);
    ?>

    <script type="text/javascript">
        var totalWords = <?php print($count); ?>;
        function updateCounter() {
            totalWords = totalWords + 1; // need to do something here to update to the real word count instead of incrementing by 1 each second
            document.getElementById("carb").innerHTML=totalWords; }
    </script>
</head>

<body onload="setInterval('updateCounter()', 1000);">
    <div class="count">
            <span id="carb">
                Loading Word Count...
            </span>
    </div>
</body>
</html>

I just need to be able to make this figure update "live" with the real value of words translated instead of a "fake" live incrementation using setInterval('updateCounter()', 1000).

So yeah, I really just need to update the function to update that word count value to the ratio of the current time against my start date.

Could anyone help me achieve this? I'm sure it's something really simple to do but I'm racking my brains to no avail. Let me know if clarifications are needed to explain what I want to do!

Thanks in advance

2
  • don't get it, if you calculate the words translated number based only on the time, you dont need PHP, or maybe just when you load the page to have the server time. If i'm wrong where do you store the value totalWords ? Commented Mar 7, 2014 at 19:23
  • Not sure what you're asking... I don't think I need to store totalWords anywhere as it's calculated on page load - or do I? Commented Mar 7, 2014 at 19:27

2 Answers 2

2

There's no need for both PHP and Javascript for this, since you're not actually getting any values from your server - it's all being calculated in a vacuum.

Fundamentally, this is a math problem. Javascript calculates the differences in dates in milliseconds, so you first need to know the number of words per millisecond you translate: words per year / days per year / milliseconds per day. I used 31556900 as the words per year value to test, since that's the number of seconds in a year.

Next, you have to apply that total to the current date - the start date, and set that as your starting total.

Finally, create an interval function that adds the number of words to the total.

This should do it:

;(function() {
    // Constants
    var   wpm = (31556900 / 365) / 86400000 // Words per year / days per year / milliseconds per day
    ,   start = new Date('January 1, 2004');

    var now = new Date()
    , total = Math.round((now - start) * wpm);

    var dom = { 
        counter: document.getElementById('counter')  
    };
    dom.counter.textContent = total;

    setInterval(function() {
        total += Math.round((new Date() - now) * wpm)
        dom.counter.textContent = total;
        now = new Date();
    }, 1000)
}())

http://jsfiddle.net/PjmwD/

Sign up to request clarification or add additional context in comments.

5 Comments

var wpm = (words_per_year / 365) / 86400000
Side note - if your average number of words per year is around 10,000, you may want to forego the interval, and just calculate the number of words on page load. At 10,000 words, you're only averaging about 1 word per hour.
It's closer to 500,000 actually, that was just for the sake of the example -- and hence the reason to want to see it update live :)
I created a dummy file with each of your solutions, entered the same start date and same number of words per year, and they display different numbers at a given time... weird
Thank you both for your input and help!
1

you can try this, i just translate your PHP code in javascript and calculate your "totalWords" base on the server time.

<script>
var getServerTime = (function () {
    var baseTime = <?php echo time() * 1000; /* convert to milliseconds */ ?>,
        startTime = new Date().getTime();

    return function () {
        return baseTime + (new Date().getTime() - startTime);
    };
}());

var calculateTotalWords = function() {

    var currentServerTime = getServerTime();
    var start = new Date(2004, 0, 1);
    var wordsPerYear = 500000;
    var SecondInYear = 31556926; 
    var wordsPerSecond = wordsPerYear / SecondInYear;
    var delay  = (currentServerTime - start.getTime()) /1000;
    var count =  delay * wordsPerSecond ;   

    return Math.round(count);
}

var interval = setInterval(function(){
    var count = calculateTotalWords();
    document.getElementById("carb").innerHTML = count;

}, 1000);

</script>
</head>

<body>
    <div class="count">
            <span id="carb">
                Loading Word Count...
            </span>
    </div>
</body>
</html>

FIDDLE DEMO

4 Comments

I'm confused, the code you provided doesn't update live -- only on page load. Or am I missing something?
as @Kadjar explain the first calculation with a delay in days couldn't work. I modify the calculation.
but if im not wrong with 500 000 words per year it still only 0.95 word per minute. It will not update so much.
You are right. I asked for confirmation though and the number of words per year is over 2 Million, so I was completely off (I just did an estimate off the top of my head)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.