I have an own PHP loginsystem. Users will be logged out after 5 min of inactivity.
Now I want to show a timer in the right top corner to display the countdown.
At the moment I am using javascript.
Like this (Pseudo, haven't my code here at the moment):
var myTime = <?php echo time(); ?>;
window.setInterval(myTime = myTime - 1; $("#timertext").text(myTime), 1000);
But I don't like this solution. I would like to use the current system time (php) and subtract the time, the user was active at last.
I found a solution to get the current system time via Ajax. But is this a good idea?
What do you think I could do to realize this counter? Is there a smart solution? Maybe a completely other way?
Related
I'm making a simple game which generates random numbers and user has to enter a value, if users value matches the random value generated, the user wins basically this is a beginner project. I want to make a small counter so that user has a limited time to put in the value and I want that limited time to show on the screen in a label. Lets say that you have to put the value under 30 secs and the timer will count from 1 to 30 every second. The counting from 1 to 30 will update in the label every second. This is the logic I'm trying to work on right now and I can't figure out any other way... If I've done some mistake in code please comment or if you have much more simpler way please post it down below. (pls dont vote down im at threat of account suspension)
Heres the part of my timer code:
if(timer <= 30)
{
for(var i = 0;i >= 30;i++)
{
setInterval(null,1000);
timer++;
document.getElementById("counter").innerHTML = timer+" seconds wasted";
}
alert("Time is over, you lost by "+s);
}
You could create a recursive function.
Say var countDown function(){ time = time--;
setTimeout(countDown, 1000);}
Then you need a variable time that is accessible for the countDown function.
var time = 30;
In the countDown function you could create an updateTimeElement.
Try it out.
The setInterval function has 2 parameters, a callback (an anomynous function in javascript thats triggered) and the milliseconds between each trigger of the interval.
What you are doing in your script is making an interval with nothing to do each second (this runs indefinately), then increment the timer integer and updating the DOM. However, this all executes within seconds.
I'd suggest (before you use a function) you look at the documentation to see how you can improve your script to work as you intent to ;-) Here are a few links that might help you get started:
http://www.w3schools.com/js/js_timing.asp
https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/
I wont be doing the work for you, since this is a good exercise for a beginner programmer ;-)
If you can't figure it out, leave a comment below this answer and I'll get back to you to help you if you need further assistance.
At our office we check in by opening a webpage and clicking on a check-in button.The following function is called while clicking the button:
function checkInOutSubmit(thisController, thisAction, checkName){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset() / 60;
var timeZone = jstz.determine_timezone();
var timeZoneName = timeZone.name();
var checkInCheckOut = checkName
jQuery.ajax({type:'POST',data:{checkInCheckOut:checkInCheckOut,currentController: thisController,currentAction: thisAction,timez:timeZoneName}, url:'/pms/attendanceForgot/checkInCheckOut',success:function(data,textStatus){jQuery('#successdiv').html(data);successCheckInOut();},error:function(XMLHttpRequest,textStatus,errorThrown){}});
}
But I want to put a old time when clicking on the button and not the current time.(If I reach click the button at 11:00am, I want to post 10:00am as my checkin time).
How can this be done?
There is not enough information here to answer your question.
All this code is doing is finding the current time zone, not the current time. It passes that to the server via an ajax request, which makes me think the time is generated server side. It's possible you could alter the logged time on the server by changing the timezone to an offset that would make it look like you are clocking in at the right time, but it would have to be some seriously deficient code on the server for that to work.
In almost all likelihood, the server is storing the time of the request in universal time as the clock in time and when you leave it's storing the time you leave in universal time as well. (think a point in time that isn't dependent on timezones) If your goal is get more hours, you'll just have to work later when you come in late. If you want it to look like you came in "on time", then changing the timezone might help until they notice that you've been there from 10am to 6pm but are only logging 7 hours.
My script has a countdown timer, but has to be controlled by the server since the time can change at any time.
Usually counts down from 1 hour, but as it gets closer to 0, a user fired event from PHP will reset the time on MySQL database and the timer will shoot back to what ever time.
setInterval(function() {
$('#timer').load('api/getdata.php?clock=1');
}, 600);
As you can see, currently the countdown is returned by a PHP script, which is called every 600ms (1000ms sometimes appears to skip a second).
I need to have a simple text countdown (Minutes and seconds), which synchronizes with the PHP script. But as it gets less than 30 seconds, would need to sync every second.
Is this possible with JS?
This is the code for the PHP
$from = time();
$to = strtotime($row['clock']);
$Timer = date('i:s', $to - $from);
echo("$Timer");
I think the easiest way to tackle this ( correct me if I'm wrong anyone! );
Fetch the time from the server
Return [ json ]
[server_time]
[seconds_left]
[miliseconds_left]
Set these values on a function and make sure its called as your contract requires. As soon as this starts hitting < 60 seconds shorten the interval by division of (e.g. the amount of seconds, altough this might not be optimal :-) ).
60/60 = 1
50 / 60 = .73
30 / 60 = .5
etc...
If the miliseconds are really really crucial I'm afraid you would have to provide some more insight of what it actually is you are trying to accomplish?
I have been coding a penny auction site and running into a problem with the countdowns. The starting time seems to be a little different on different machines (usually a discrepancy of about a second, but sometimes 2 or 3), which obviously is a big issue for bidders. I'm thinking a big part of the answer is simply network lag, but (a) are there other factors involved? and (b) is there a way to correct for network lag somehow?
I've tried hitting the server via an Ajax call every second, and that works well enough (though there's always a bit of lag) but I'd rather not have to do that because it'll be hard on the server.
JavaScript development is not my forte, so I'd appreciate any tips and feedback!
Here's my code, as generated on the server
jQuery(document).ready(function() {
var aid = " . $aid . ";
var loadTime = Math.floor(jQuery.now()/1000);
//alert(loadTime);
serverTime = " . time() . ";
var clockDiff = loadTime - serverTime;
var diff;
auctionExpirationValue" . $aid . " = " . $expiry . ";
var newServerTime = setInterval(function() {
diff = window['auctionExpirationValue' + aid] - Math.floor((jQuery.now())/1000) + clockDiff;
diff_string = parse_countdown(diff);
jQuery('#auction-expiry').html(diff_string);
},1000);
});
the clockDiff variable is to account for any clock differences between the user's machine and the server. Obviously, if one machine is ahead or behind the user would see different values in the countdown.
As you can see, the code loops every second (or, more or less every second, I understand it's not exact), calculates the difference between now and the auction expiry (compensating with clockDiff), formats it and displays it. Pretty simple. The auctionExpirationValue*** global variable is used to store the auction expiry time locally as a timestamp.
My client has also informed me that on his iPad, the countdown would sometimes drift a little, in addition to the original discrepancy. What's the explanation there?
I am developing a bidding system on Google App Engine with Python. A product is opened for bidding at a predefined time and the bidding lasts for 3 minutes. The price of the product drops down every second by a constant value in the 3-minute period until it is zero. And the bidder who presses the "Bid" button first wins the bid. One critical issue in this application is that the time among all users should be perfectly synced so that everybody sees the same price at the same time. The following is what I have come up so far but it suffers from inaccurate timers.
When a user visit or refresh the page, the Python code will pass the sever time to the javascript timer and the timer starts to count down. The simplified javascript is as follows:
var count = {{timeToBid}}; // 'timeToBid' is in seconds and is inserted by the template engine
var price =={{initialPrice}} // The initial product price
var currentPrice; // Current price
function updateTime() {
timeStr = ...; // Set the time string to be HH:MM:SS
$("#timeToBid").html(timeStr); // Display time in the 'timeToBid' div
if (count <= 180) { // Start bidding
currentPrice = ...; // Calculate the current price
$("#currentPrice").html(currentPrice); // Update current price
}
count--;
setTimeout(updateTime, 1000); // Executed every second
}
updateTime();
The above javascript suffers significantly from unsynced timers among user browsers, as well as unsynced server times (see this). The current price displayed in each browser can vary in a huge range which makes the system totally unusable. This is a rather complicated problem and I am asking for good solutions. One or two seconds time inaccuracy is acceptable. My questions:
(a) To make the javascript timer more accurate, I plan to use AJAX to retrieve the server time every 10 seconds and then update 'count'. Is this a good solution? Or there are other options?
$.ajax({
url: "/getServerTime",
cache: false,
success: function(serverCount) {
count = parseInt(serverCount);
return false;
}
});
(b) I have absolutely no idea how to solve the server time inconsistency problem. Can anybody help? Thanks.
System clocks on App Engine servers are kept in sync: see this authoritative answer.
Every App Engine HTTP response has a Date header, like this Date: Wed, 24 Apr 2013 06:03:37 GMT. You can use this to sync browser with server time.