i have a question about a javascript/php cron issue. well its not an issue per se but in my case it is.
i have the below javascript that sets a cookie and counts down till the end of that cookie's time. in my case its 10 minutes.
I also have a cron file that runs every 10 minutes.
I would like to synchronize the countdown with the cron file.
The below script works well when i call it from the page however it counts down from the time the user visits the page and its out of sync with the cron file im running.
i understand this is not a php question but the pages im displaying the scripts are php.
Any pointers for me?
Help would be greatly appreciated.
Thank you for reading.
All i have is below.
<div id="countre4">
<script type="text/javascript">
function setCookie(c_name, value)
{
var exdate = new Date();
exdate.setDate(exdate.getDate() + 14);
var c_value = escape(value) + "; expires=" + exdate.toUTCString();
document.cookie = c_name + "=" + c_value;
}
function mycountre(countdownId, countdownTarget, countdownSeconds, countdownLooping){
var countre = document.getElementById(countdownId); // get html element
if (!countre) {
return;
}
var target = countdownTarget; // target time
var intervalId; // id of the interval
setCookie("time", target);
// update function
function updatecountre(){
var time = Math.floor((target - new Date().getTime()) / 1000); // countdown time in seconds
if (time < 0) { // if countdown ends
if (countdownLooping) { // if it should loop
target += 1000 * countdownSeconds; // set new target time
time = Math.floor((target - new Date().getTime()) / 1000); // recalculate current time
setCookie("time", target);
} else { // otherwise
clearInterval(intervalId); // clear interval
time = 0; // set time to 0 to avoid displaying negative values
}
}
// split time to seconds, minutes and hours
var seconds = '0' + (time % 60);
time = (time - seconds) / 60;
var minutes = '0' + (time % 60);
time = (time - minutes) / 60;
var hours = '0' + time;
// make string from splited values
var str = hours.substring(hours.length - 2) + ':' + minutes.substring(minutes.length - 2) + ':' + seconds.substring(seconds.length - 2);
countre.innerHTML = str;
}
intervalId = setInterval(updatecountre, 200); // start interval to execute update function periodically
};
var parts = document.cookie.split(';');
var cookie = new Date().getTime() + 1000 * 15 * 60;
for (var i = 0; i < parts.length; ++i) {
if (parts[i].trim().indexOf('time') == 0) {
var value = parts[i].trim().split('=');
cookie = parseInt(value[1]);
}
}
mycountre(
'countre4', // id of the html element
cookie,
10 * 60, // time in seconds (10min here)
true // loop after countdown ends?
);
</script>
</div>
Maybe you should rethink your approach. Don't use a cookie for a piece of information actually stored on the server.
How about instead of a cookie, each PHP page simply set a global JS variable for how much time you have left. Something sorta like this:
<script>
var timeLeft = <? echo $timeLeftInMilliseconds ?>;
startCounter(timeleft);
</script>
Then your counter script can read that and animate a counter accordingly. This leaves it up to your server side code to accurately deliver when the next cron will happen.
Related
I'm trying to set up counter logic for a game. The critical point here is that every user who enters this page sees the same second at that moment. I will have a counter that counts down from 25 and everyone will place their bets during this time. When the 25 seconds are over, a 10 second counter will start, during which 10 seconds the winning bet will be announced. How can I set up the database setup so that these counters are repeated continuously?
I am using the following code for javascript, but every time I enter the page it starts from 25
var interval = 25000;
var interval1 = 10000;
var endTime;
function millisToMinutesAndSeconds(millis) {
// Use floor instead of toFixed
var seconds = Math.floor((millis % 60000) / 1000);
return (seconds < 10 ? "0" : "") + seconds;
}
function reset() {
// Use Date.now() instead of +new Date()
// And create a cycle length that covers both intervals
endTime = Date.now() + interval + interval1;
}
reset();
setInterval(function () {
var remaining = endTime - Date.now();
if (remaining >= 0) {
// Adjust the time to display
// depending on where in the total interval we are:
if (remaining >= interval1) remaining -= interval1;
document.getElementById("timer").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset()
}
}, 100);
You just need to put the end date and time in database. The countdown must be done with javascript.
Get the date from backend (database) with php and pass it to javascript. Then do the countdown with js.
This tutorial seems exactly like what you need.
Hello I need to spend a given XML through javascript to subtract the current date and time date.
What makes this code is to show the remaining time of a song streaming in minutes and seconds
And then with javascript parsing date and I transform in milliseconds and the current date will also rest in ms.
In Chrome date shows me perfectly, but in Mozilla and IE NaN console shows me and gives error.
I do not understand is that if I have parsed the date because it only works in Chrome. There must be a mistake.
PHP (I draw the start date of a song)
<?php
$xml = # simplexml_load_file('http://www.example.com');
foreach ($xml as $track){
$startTime = $track->starttime;
$songDuration = $track->playduration;
}
?>
JAVASCRIPT:
var spend javascript
var tiempoComienzo= "<?php echo $startTime ?>";
var cancionDuracion="<?php echo $songDuration ?>";
//parse delivered date from php
var d = new Date(Date.parse(tiempoComienzo));
//PHP get the date in milliseconds
var resultPHPms = d.getTime();
//get the current date
var f = new Date();
//step the current date to milliseconds
var resultJSms = f.getTime();
//adding the date of the song to the length of the song
var inicioMasCancion=parseInt(cancionDuracion) + parseInt(resultPHPms);
//It is the challenge to the current date
var TiempoRestante=inicioMasCancion-parseInt(resultJSms);
//pass the result to seconds
seconds=(TiempoRestante/1000)
var container = document.getElementById('time');
var seconds = parseInt(seconds+7);
//step seconds to minutes and seconds
var minutes = parseInt( seconds / 60 ) % 60;
var seconds = seconds % 60;
var contadorDeTiempo=(minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
countdown(seconds);
function countdown:
<script>
var timer;
function countdown(seconds) {
seconds--;
if(seconds >= -1) {
container.innerHTML =contadorDeTiempo;
}
}
timer = setInterval(countdown, 1000);
</script>
HTML:
<span id='time'></span>
In chrome it is perfectly displayed and works perfect. But in Mozilla and IE console NaN it is shown, specifically in this line:
var d = new Date(Date.parse(tiempoComienzo));
How I could solve? The resulting XML date is as follows:
2015-12-20 12:45:33.17
thanks very much for your help
This project includes creating a form for users to enter the start and end time of a promotion. The site where the promotion will be live operates in the Pacific Time Zone and the user creating the promotion could be anywhere in the world.
The start time must be one hour greater than the current PST (or PDT depending on season). The current method of validating the start time is not working because it pulls the local time of the user's computer.
I need a way to compare the user's local time to Pacific Time and validate that the promotional start time is one hour greater.
My working theory is to find the offset between the user's local time and GMT time, then find the offset between current Pacific time and GMT (which varies by 7 or 8 hours depending on DST--right?), then apply these offsets to the user's time and compare to Pacific time plus one hour.
I have succeeded in finding the necessary offsets and alerting the correct current time in Pacific time in various strings and timestamps but the overall logic escapes me. Also, I have been unable to successfully add one hour to a TimeStamp.
this question is similar, and many others, but in this case the OP has a fixed offset:
Compare user's time zone with the website's office location time zone
Current code:
function valid() {
var starttime=$('#1-PromotionalSaleStartTime').val();
var endtime=$('#1-PromotionalSaleEndTime').val();
var now = new Date();
var hour= now.getHours();
var min = now.getMinutes()+10;
var nows= parseInt(hour)+1;
var time=nows+':'+min;
var presentime = now.getHours()+':'+now.getMinutes()
var month =now.getMonth()+1;
var day = now.getDate();
var output = (month<10 ? '0' : '') + month + '/' +(day<10 ? '0' : '') + day + '/' + now.getFullYear() + ' '+time;
var now = (month<10 ? '0' : '') + month + '/' +(day<10 ? '0' : '') + day + '/' + now.getFullYear() + ' '+presentime;
var present = new Date(now);
var oneDay = 24*60*60*1000; // hours*min*sec*milliseconds
var firstDate = new Date(starttime);
var secondDate = new Date(endtime);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
var diff = Math.round(Math.abs(( present.getTime() - firstDate.getTime())/(oneDay)));
var presentTimeStamp = +'<?php echo time(); ?>' * 1000;
var firstDateTimeStamp = Date.parse($('#1-PromotionalSaleStartTime').val());
var err = 0;
<?php if($this->add!="" && isset($this->add)) {?>
if(presentTimeStamp > firstDateTimeStamp) {
$('#1-PromotionalSaleStartTime').after('<ul class="errors"><li>Sorry, but you cannot add past date.</li></ul>');
err++;
}
<?php } ?>
if(diffDays==0){
$('#1-PromotionalSaleEndTime').after('<ul class="errors"><li>The date difference between Start and End dates should be 24 hours.</li></ul>');
err++;
}
if(starttime < output){
$('#1-PromotionalSaleStartTime').after('<ul class="errors"><li>Your Start time should be at least 1 hour more than the current Pacific Time like. '+ output +'</li></ul>');
err++;
}
if((Date.parse(starttime)> Date.parse(endtime)) ){
$('#1-PromotionalSaleEndTime').after('<ul class="errors"><li>End Time cannot be less than Start Time plus 1 day.</li></ul>');
err++;
}
Try this on the Server side:
/* timetest.php */
<?php
if(isset($_POST['dateInfo'])){
date_default_timezone_set('America/Los_Angeles'); $data = array();
$dt = new DateTime;
$pacificPlusOneOffset = dt->add(new DateInterval('P1D'))->getOffset();
$data['diff'] = +$_POST['dateInfo']-$pacificPlusOneOffset;
echo json_encode($data);
}
else{
// could be some kind of hack
}
?>
AJAX should send JavaScript on the Client side, like:
var pre = onload;
onload = function(){
if(pre)pre();
// more code to run other code here
function post(url, send, success){
var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP'), ec = [], s;
for(var i in send){
ec.push(encodeURIComponent(i)+'='+encodeURIComponent(send[i]));
}
s = ec.join('&').replace(/%20/g, '+'); x.open('POST', url);
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.setRequestHeader('Content-length', s.length);
x.setRequestHeader('Connection', 'close');
x.onreadystatechange = function(){
if(x.readyState === 4 && x.status === 200 && success){
success(eval('('+x.responseText+')'));
}
}
x.send(s);
}
post('timetest.php', {dateInfo:new Date().getTimezoneOffset()}, function(result){
console.log(result.diff);
})
}
I have a requirement to make a countdown timer that automatically restarts when the time has elapsed.
For example, I need to countdown from 3pm or 15:00 UK time and reset to start counting again when the time has reached.
I've been trying with some jQuery but that will show browser time and not server time. If anyone is able to share a solution please let me know.
Thanks in advance!
The code below is a working example from which works perfectly: https://gist.github.com/Majestik/3964527
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown() {
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 5) ) { // Monday to Friday only
var target = 15; // 15:00hrs is the cut-off point
if (now.getHours() < target) { // don't do anything if we're past the cut-off point
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}
}
}
var timerRunning = setInterval('countDown()', 1000);
}
Time remaining: <span id="countdownTimer"><span>00:00.<small>00</small></span>
In your PHP code when you are writing the HTML that includes this javascript file just set the variables there rather than getting javascript to do it once it has loaded, this way you are using your server time rather than the browser time.
I need to build a countdown timer in jquery that replaces the html in a span tag from a php variable that's formatted to XX Days XX:XX:XX. It should load the variable on page load and then when the jquery script loads it starts the countdown but keeping the same format (XX Days XX:XX:XX) and eventually displays "Expired" and stops the countdown.
I have a jsFiddle started (http://jsfiddle.net/2SDdh/1/) but it shows the formatted time and then loads a 10 sec countdown and eventually shows "Expired". Anyone know how to get the formatting correct?
My HTML output via PHP
<span class="exp">10 Days 10:10:10</span>
My jQuery
$(function(){
var count = 10;
countdown = setInterval(function(){
if (count > 0) {
count--;
$(".exp").html(count);
} else {
$(".exp").html('Expired');
}
}, 1000);
});
try this
html:
<span class="days">10</span> Days <br />
<span class="exp">23:59:59</span>
javascript :
$(function(){
var days = 10;
var count = 86399;
var count2 = 0;
var hour = 0;
var min = 0;
var sec = 0;
countdown = setInterval(function() {
if (days != 0 || count != 0) {
if (count == 0) {
days--;
count = 86399;
} else {
count--;
}
count2 = count;
hour = Math.floor(count2 / 3600);
count2 = count2 % 3600;
min = Math.floor(count2 / 60);
count2 = count2 % 60;
sec = count2;
$(".exp").html(hour + ":" + min + ":" + sec);
$(".days").html(days);
} else {
$(".exp").html('Expired');
}
}, 1000);
});
Cheers!
Instead of rolling your own countdown timer, why not use one that already exists?. KK Countdown works well for me.