Search code examples
javascriptphpjquerycountdown

Countdown JS+PHP, what's wrong?


I'm trying to make this function work but i don't know what's wrong and i'm not really good at js. I want to do call my timer function with number of seconds to countdown from the span id "count".

Example:

<p id="hello">Wait <span id="count">5</span> secs</p>

<?php
echo '<script type="text/javascript">'
   , 'timer(5);'
   , '</script>';
?>
<script>
function timer(tiempo){

  setInterval(function() {
    tiempo--;
    if (tiempo >= 0) {
      span = document.getElementById("count");
      span.innerHTML = tiempo;
    }
    // Display 'counter' wherever you want to display it.
    if (tiempo === 0) {
      window.location.reload();
        clearInterval(tiempo);
    }

  }, 1000);

});
</script>

What's wrong?


Solution

  • Define the function before it's called:

    <script type='text/javascript'>
    function timer(tiempo){
      setInterval(function() {
        tiempo--;
        if (tiempo >= 0) {
          span = document.getElementById("count");
          span.innerHTML = tiempo;
        }
        // Display 'counter' wherever you want to display it.
        if (tiempo === 0) {
          window.location.reload();
            clearInterval(tiempo);
        }
    
      }, 1000);
    
    }
    </script>
    <p id="hello">Wait <span id="count">5</span> secs</p>
    
    <?php
    echo '<script type="text/javascript">'
       , 'timer(5);'
       , '</script>';
    ?>