Timer always starts at 60 minutes

Hello,
This is some test code that is not producing the results that I expected. The program starts a session and then checks to see if a session variable has been created, if not , it uses the time() function to get a timestamp and assigns that to the session variable and then assigns this timestamp variable a variable called $currentTimeStamp and then assigns this value to another variable called $startTimeStamp. Then it assigns the value of 0 to a variable called $elapse since no time has elapsed on the start of the program. Next the program uses the $elapsed variable in a javascript routine that I found online but modified it slightly. Then it outputs an html page via heredoc. On the initial start the program works as I would expect, but on refresh, I would expect the elapsed time to be deducted from the start time but this is not occurring. However, when I uncomment this line: //$elapsed = rand(10, 1000000); the program works exactly as I would expect it to (I did this just for a test) the timer starts at random times or the timer never starts as you might expect because of the random values, but when I uncomment this line, the timer always starts from the beginning as if the program is ignoring the $elapsed variable even though you can plainly see from the test output that the $elapsed variable value is increasing on each refresh of page. This does not make sense to me. Here is the code with the test variables output to the html:

<?php
session_start();

if (isset($_SESSION['startsession'])){
	$startTimeStamp = $_SESSION['startsession'];
	$currentTimeStamp = time();
	$elapsed = $currentTimeStamp - $startTimeStamp;
}

else{	
	$_SESSION['startsession'] = time();
	$currentTimeStamp = time();
	$startTimeStamp = $currentTimeStamp;
	$elapsed = 0;
}
//$elapsed = rand(10, 1000000);
$myStuff = <<< A1a

<script>
// Set the date we're counting down to
var countDownDate =new Date().getTime() + (3.6e+6 - $elapsed);

// 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 and 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 = 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>
A1a;
echo <<< myVar
<html>
<head><title>My Head</title></head>
<body>
$myStuff
<p id="demo"></p>
<p>Body page 1</p>
<a href = "timerTestPhp.php">Go Back</a>
<p>
StartTimeStamp: $startTimeStamp
</p>
<p>
CurrentTimeStamp: $currentTimeStamp
</p>
<p>
Elapsed: $elapsed
</p>
</body>
</html>
myVar;
?>

Hello and welcome to PHPHelp,

Now, let’s take a moment to clarify some things:

  1. time moves forward. the increased $elapsed variable is doing what it is supposed to do according to your code: hold the difference between the session timestamp and the current timestamp. How is this surprising to you? time moves forward, thus, this is the expected result.

  2. explaining what the code is doing is only helpful if you haven’t posted code. I can see that your setting variables, so need to explain it in your post. What i don’t know is what are you trying to accomplish? it sounds like you want a time limit but i don’t know because you have yet to mention what you are trying to accomplish.

  3. the code can be optimized, even if the code is not doing what you want. like so:

<?php
  session_start();

  if (isset($_SESSION['startsession'])) {
      $elapsed = time() - $_SESSION['startsession'];
      echo 'see how time moves forward?' . $elapsed;
  } else {
      $_SESSION['startsession'] = time();
  }
  exit;
?>

if you are trying to set a time limit then just add the time limit to time:

$timeLimit = 1800;
$timeLimit += time();

then you can deduct the $timeLimit from a current timestamp.

If $timeLimit < time() then all is good else time has expired.

so perhaps you can expand a bit on what you are trying to accomplish using timestamps.

Hi John,
The increasing value of the $lapsed time variable is not what is surprising me.

then this is javascript question, not php.
just deduce the session time from the javascript time instead.

Wow! Thanks for your help.

okay. you are entitled to your opinion. i’m not thin-skinned. I’m not trying to upset you. I think that you are making this more complicated than what it is. why give up? try to solve the problem.

all is good. many members here that can help you if you don’t like my reply. maybe i’m being curt. sorry if you think i’m rude.

You obviously did not read my post–just jumped to an erroneous conclusion so I’m just wasting my time here. Cheers

what? i’m not an admin. I don’t have authority here. I’m just a normal member. why would you think that i’m an admin. I have no powere here. I’ve been a moderator before on other forums and i don’t just delete posts. But why would you think that i’m an admin?

anyway, sorry if you think i’m rude.
please repost your code and i’ll let other members reply to you.
don’t give up. keep fighting :slight_smile:

i just noticed that i have some sort of regular member status, so maybe this is why you think i’m an admin. Again, i am not an admin but even i were an admin: disagreements or misunderstandings are not grounds for deleting posts. we don’t want a hostile environment here. All is good. I’m not mad and i’m not offended. All is good.

please repost your code and wait for other replies.

kdE8vR5

2 Likes

not sure why. i’m tired today, so maybe i am being curt?
whatever. i am not mad. just repost and wait for other replies. what is the big deal?
i’m sure that someone will help out. I just see the code doing what it is supposed to do.

Ok, I’ll try this again.

yeah, copy and pasting everything will solve any problem here… /irony

1 Like

I figured it out. WTF! Will post code later

This code has not been cleaned up, but it does exactly what I wanted it to do now.

    <?php
    session_start();
    if (isset($_SESSION['startsession'])){
    	$startTimeStamp = $_SESSION['startsession'];
    	$currentTimeStamp = time();
    	$elapsed = $currentTimeStamp - $startTimeStamp;
    	$elapsed *= 1000;
    }

    else{	
    	$_SESSION['startsession'] = time();
    	$startTimeStamp = time();
    	$elapsed = 0;
    }
    ?>
    <html>
    <head><title>My Head</title></head>
    <body>
    <script>
    // Set the date we're counting down to
    var elapsed = <?php echo json_encode($elapsed);?>;
    var sixtyMins = 3.6e+6;
    elapsed = sixtyMins-elapsed;
    var countDownDate = new Date().getTime() + elapsed;
    // 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 and 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 = 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>

    <p id="demo"></p>
    <p>Body page 1</p>
    <a href = "timerTestPhp2.php">Go Back</a>
    </body>
    </html>

OP, I am an Admin and this forum is no place for the kind of post you made. If you want to be a part of this forum then keep it civil. People on this forum, admin or not, volunteer their time for free to help others.

2 Likes

Great that you got it to work. Couldn’t you just subtract 1 second in each iteration of the loop instead of recalculating it? Kinda edging on premature optimization but potentially unecessary code in loops really itches me ^^

1 Like

And because I have earned my Asshole Badge MANY TIMES and am a moderator, I will revert your post back to what it was, rather than showing your multiple edits.

Cheers!

1 Like

Hello and good day to everyone,

i am not sure what happened here. I guess the OP thinks i was rude or something. I think that i need to read over my replies and check for rudeness. I don’t want a negative view from this community. I love this forum and i think that we generally have a great community here. I don’t want to be the center of a quarrel. My apologies to all of our members.

Meantime, i have checked my badges page and i don’t see that one listed. :slight_smile: perhaps it’s an alias of Appreciated. I don’t know.

honestly, i was trying to be helpful and point out that i see the problem with javascript. I am not a javascript guru, so i could be wrong, but i believe that the epoch time in javascript includes milliseconds. yes? so the two time stamps don’t match in the first place. right? document.write() should show the resuls. I don’t remember if Math.round /1000 is used or not to get the time without milliseconds. Anyway, i noticed that the javascript is not correct. Furthermore, i didn’t see a need for the variables or the heredoc. I guess i seemed rude.

Hi John,
I’ll accept the blame for being rude. The problem with the first code I posted was the difference between the php timestamp and the javascript timestamp. I had not noticed my logic error at first but I kept at it till it dawned on me what the problem was. Thanks for your help though.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service