1

I am trying to create a countdown timer using a javascript code i found on W3Schools. The code has always worked for me, but now, I need to create the timer inside a php loop which displays comments in a page. This means that the javascript timer code has to be unique for each comment, and I have done with I feel is right, but it just won't work. Here is what I have:

<?php 
$post_comments = $this->db->get_where('post_comments', array('display' => 'true'))->result_array();
foreach ($post_comments as $comment) { ?>
    Expire time - <span id="cRemTime<?php echo $comment->id; ?>" style="color: red"> </span>

    <?php
    $comment_stop_time = date("M j, Y H:i:s", strtotime($comment->time. '+1 hours'));  //timestamp from table + 1 hour
    ?>

    <script>
    var ExhaustTime = "<?php echo $comment_stop_time; ?>";
    var countDownDate = new Date(ExhaustTime).getTime();
    var x = setInterval(function() {
        var now = new Date().getTime();  
        var distance = countDownDate - now;    
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);   
        document.getElementById("cRemTime<?php echo $comment->id; ?>").innerHTML = hours + ": " + minutes + ": " + seconds;
        if (distance < 0) {
            clearInterval(x);
            document.getElementById("cRemTime<?php echo $comment->id; ?>").innerHTML = "Exhausted!";
        }       
    }, 1000);
    </script>

<?php } ?>

What am I missing?
Note: I use Code Igniter

2
  • Have you looked at the outputted javascript code by viewing the page source code? Are you seeing in any errors in the console? Commented Sep 22, 2017 at 21:54
  • the js vars you define (all of them! including the setInterval function) are global, meaning they should exist only once. So only the last one will be 'valid'. You could fake-'namespace' them the same way as you do with the span Commented Sep 22, 2017 at 22:10

1 Answer 1

1

The javascript vars you define (all of them, including the x= setInterval()) are global, meaning they should exist only once. So only the last one will be 'valid'. You could fake-'namespace' them the same way as you do with the span:

var ExhaustTime<?php echo $comment->id; ?> = "<?php echo $comment_stop_time; ?>";
// the same for countDownDate and x (the setInterval)

This of course is not an elegant solution, but it'll make it work I think.

An elegant solution would wrap all of that in a class or in a function that you pass the params to in every loop. So you'd have that object only once, but call it in every loop (like an init-function maybe)

A primitive version of such could be something like this:
(not tested)

// OUTSIDE php foreach loop, so only once in a <script>
function MyCounter(exhaustTime,elementId) {

    // this.ExhaustTime = exhaustTime; // there's no need for that extra var
        // you might want to check here if you got a valid exhaustTime (or later countDownDate).

    this.countDownDate = new Date(exhaustTime).getTime();
    this.init = setInterval(function() {
        var now = new Date().getTime();  
        var distance = this.countDownDate - now;    
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
        // better find that element only once and re-use it
        var target = document.getElementById(elementId);
        target.innerHTML = hours + ": " + minutes + ": " + seconds;
        if (distance < 0) {
            clearInterval(x);
            target.innerHTML = "Exhausted!";
        }       
    }, 1000);

}

// inside your php foreach loop (and in a <script>)
var Counter<?php echo $comment->id; ?> = new MyCounter(<?php echo $comment_stop_time; ?>, "cRemTime<?php echo $comment->id; ?>");
Counter<?php echo $comment->id; ?>.init();

For further reading: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS

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

Comments

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.