1

I am trying to follow a jsfiddle example to create a time in javascript:

http://jsfiddle.net/g3rRJ/

Now obviously the timer in the jsfiddle works fine. But the issue I have is that the time which the timer starts from comes for a mysqli/php variable where it retrieves the time from the db.

So except for:

<span id="countdown">01:30:10</span>

I have to have it as:

echo "<p><span id='countdown'>" . $dbSessionDuration . "</span></p>";

AND

except for:

var time = "01:30:10",

I have to have it as:

var time = <?php echo json_encode($dbSessionDuration); ?>,

Now I am getting no errors but what is happening is that the timer is not doing a count down. My question is why is it not counting down? An example of the time from the variable could be 01:00:00.

Below is the code for the function:

echo "<p><span id='countdown'>" . $dbSessionDuration . "</span></p>";


...

         <script type="text/javascript">


    (function(){
  $(document).ready(function() {
    var time = <?php echo json_encode($dbSessionDuration); ?>,
      parts = time.split(':'),
      hours = +parts[0],
      minutes = +parts[1],
      seconds = +parts[2],
      span = $('#countdown');

    function correctNum(num) {
      return (num<10)? ("0"+num):num;
    }

    var timer = setInterval(function(){
        seconds--;
        if(seconds == -1) {
            seconds = 59;
            minutes--;

            if(minutes == -1) {
                minutes = 59;
                hours--;

                if(hours==-1) {
                  alert("timer finished");
                  clearInterval(timer);
                  return;
                }
            }
        }
        span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
    }, 1000);
  }); 
});

</script>
0

2 Answers 2

1

Change this:

  }); 
});

</script>

to this:

  }); 
})();            //  ←  note the extra parentheses

</script>

so that you actually call your anonymous function. (Alternatively, you can simply remove its (function(){ and }); entirely. There's no reason for this code to be in a function at all.)

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

Comments

1

I don't know if this was a mistype but I was able to run this code by adding $, $(function(){, at the first part of your anonymous function. I'm assuming your value from the db comes in as hours:mins:secs. I'm not sure why Fiddler ran but I had to add that to get it to work in my environment.

1 Comment

Though Ruakh is correct. The code will be executed when the page has loaded if you remove the anonymous function call.

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.