Jump to content

Countdown timer Ajax and PHP


v0idmp3

Recommended Posts

Hi

 

I have a little problem. I develop browser game and I dont know how to build countdown timer. For example...When player click on "Build Something", I need to show him a countdown timer, from start time to some time in future, and countdown difference from start and end time. And than, when timer reach zero, I need to put some data in database. I think a lot about that, and I realized that I must have in my database start and end time, but I dont know how to calculate remaing time when player logout from game, and than log in again. How to show him how much time was spend when he was offline? If you know some tutorial about Ajax/JS countdown timers, I will be very thankful. I searched google, but I didnt find what I need. I'm new to ajax/js and I really dont know how to make that.

 

Cheers :)

Link to comment
https://forums.phpfreaks.com/topic/264327-countdown-timer-ajax-and-php/
Share on other sites

var timeLeft = 300; // 5 minutes
var timer = window.setInterval(function() {
    timeLeft--;
    var minutesLeft = Math.floor(timeLeft / 60);
    var secondsLeft = timeLeft % 60;
    console.log('Time left: ' + minutesLeft + ':' + secondsLeft);
    if (timeLeft == 0) {
        window.clearInterval(timer);
        // do some ajax thing
    }
}, 1000);

By the way here's the answer to your last question:

 

<?php
// Some code
$timeLeft = 300;
?>
<script type="text/javascript">
var timeLeft = <?=$timeLeft?>; // 5 minutes
var timer = window.setInterval(function() {
    timeLeft--;
    var minutesLeft = Math.floor(timeLeft / 60);
    var secondsLeft = timeLeft % 60;
    console.log('Time left: ' + minutesLeft + ':' + secondsLeft);
    if (timeLeft == 0) {
        window.clearInterval(timer);
        // do some ajax thing
    }
}, 1000);
</script>

 

But of course, your next question will be...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.