Jump to content

Javascript clock - on refresh


wilna

Recommended Posts

Hi, please excuse my lack of knowledge.  I've got a JavaScript clock on my page.  My problem is when the users refreshes my php page the clock starts from 0 again.  I need the clock to remember the value and then just continue from where it was.  I've been trying with cookies but gave up.  Can someone please help me?  I've been trying but I'm clueless.

 

Javascript

var pageVisisted = new Date(); 

setInterval(function() {
    var timeOnSite = new Date() - pageVisisted;
    
    var secondsTotal = timeOnSite / 1000;
    var hours = Math.floor(secondsTotal / 3600);
    var minutes = Math.floor(secondsTotal / 60) % 3600;
    var seconds = Math.floor(secondsTotal)  % 60;
    
    document.getElementById('counter').innerHTML = hours + ":" + minutes + ":" + seconds;
}, 1000);

 

The php page

<head>
<?php
session_start();
?>
<script type="text/javascript" src="counter.js"></script>
</head>
<body>
<?php
echo "<span id='counter'></span>";
?>
</body>

Link to comment
https://forums.phpfreaks.com/topic/249112-javascript-clock-on-refresh/
Share on other sites


function setCookie(c_name,value,exdays)
{
   if ( typeof exdays == 'undefined' )
      var exdays = 365;
   var exdate    = new Date();
   exdate.setDate(exdate.getDate() + exdays);
   var c_value   = escape(value) +";expires="+ exdate.toUTCString());
   document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
   var i, x, y, cookies=document.cookie.split(";");
   for (i = 0; i < cookies.length; i++)
   {
      x = cookies[i].substr(0, cookies[i].indexOf("=") );
      y = cookies[i].substr(cookies[i].indexOf("=") + 1);
      x = x.replace(/^\s+|\s+$/g, "");
      if (x==c_name)
      {
         return unescape(y);
      }
   }
   return false;
}


var pageVisisted = getCookie('pageVisited');
if ( !pageVisited )
   pageVisited = new Date(); 

setInterval(function() {
    var timeOnSite = new Date() - pageVisisted;
    
    var secondsTotal = timeOnSite / 1000;
    var hours        = Math.floor(secondsTotal / 3600);
    var minutes      = Math.floor(secondsTotal / 60) % 3600;
    var seconds      = Math.floor(secondsTotal)  % 60;
    
    document.getElementById('counter').innerHTML = hours + ":" + minutes + ":" + seconds;
}, 1000);
window.onunload = setCookie('pageVisited', pageVisited);

<head>
<?php
session_start();
?>
<script type="text/javascript" src="counter.js"></script>
</head>
<body>
<span id='counter'></span>
</body>

 

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.