keyur
keyur

Reputation:

Countdown Timer

My project in php

I want to create a countdown timer for asking question in limited timeframe like LMS here i have use the javascript countdown timer but when refresh the page javascript timer are reset.

Upvotes: 0

Views: 3880

Answers (4)

Akshit Ahuja
Akshit Ahuja

Reputation: 337

try this

<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 1, 2017 12:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();

    // Find the distance between now an the count down date
    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    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);

    // Output the result in an element with id="demo"

    document.getElementById("demo").innerHTML = days + "d " + hours + "h "
    + minutes + "m " + seconds + "s "; 


    // If the count down is over, write some text 
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 1000);
</script>

and also put this under body tag.

<p id="demo"></p>

Upvotes: 0

inakiabt
inakiabt

Reputation: 1963

Try something like:

<?php
   session_start();

   //to reset the saved countdown
   if (!empty($_REQUEST['resetCountdown']))
   {
       unset($_SESSION['startTime']);
   }

   if (empty($_SESSION['startTime']))
   {
       $_SESSION['startTime'] = time();
   }

   //In seconds
   $startTime = time() - $_SESSION['startTime'];
?>
<script type="text/javascript">
var countdown = 60; //in seconds
var startTime = <?php echo $startTime; ?>;

startCountdown(startTime, countdown);

function startCountdown(startFrom, duration)
{
   //countdown implementation
}
</script>

Upvotes: 1

Tom Haigh
Tom Haigh

Reputation: 57805

You could store the start time in a php session. Then everytime you load a page you can continue the countdown timer with javascript, e.g.

<?php
//on every page
session_start();

//when you start
$_SESSION['start_time'] = time();

Then on every page:

<script type="text/javascript">
    var startTime = <?php echo $_SESSION['start_time']; ?>;
    //calculate remaining time
</script>

You will need to watch for when the timezones are different, or when the client's clock is wrong. Maybe instead you could calculate the remaining time in seconds and print that into javascript on each page, but then you could have innacuracy over high latency connections etc.

Upvotes: 3

Steven
Steven

Reputation: 3843

You could also store the timer in a session variable in PHP so that when the page is refreshed the time is still preserved.

Upvotes: 0

Related Questions