Jump to content

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...

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.