|
How to prevent resetting of countdown timer on page
refresh using javascript?
Run the following html snippet, this serves your purpose. When timer starts new then no cookie will be found and it starts with a default value set (100 in this case) and stored in cookie each second. When page is refreshed then cookie is checked first for the value and takes it from cookie else starts with default value. When the time elapses (becomes 0) cookie is deleted. A cookie named timer is stored in this example: <html>
<script type="text/javascript"> function Get_Cookie( check_name ) { var a_all_cookies = document.cookie.split(
';' );
for ( i = 0; i < a_all_cookies.length;
i++ )
return cookie_value;
break;
a_temp_cookie
= null;
} if ( !b_cookie_found )
return null; } } function setCookie(name, value, path) {
function deleteCookie(name, path) { if (Get_Cookie(name)) document.cookie = name+"="+((path)?";path="+path :"")+";expires=Thu, 01-Jan-1970 00:00:01 GMT"; } var secs
function InitializeTimer() { if(Get_Cookie('timer')){ document.getElementById('cookieText').innerHTML
= 'cookie found with value '+Get_Cookie('timer');
} else{ document.getElementById('cookieText').innerHTML = 'no cookie found timer starting from default value'; secs = 100; } StartTheTimer(); } function StopTheClock() { if(timerRunning) clearTimeout(timerID); timerRunning = false; deleteCookie('timer', '/'); document.getElementById('cookieText').innerHTML = 'cookie deleted'; } function StartTheTimer() { if (secs==0) { document.getElementById('tim').innerHTML = secs; setCookie('timer', secs, '/'); StopTheClock(); } else { self.status = secs; document.getElementById('tim').innerHTML = secs; setCookie('timer', secs, '/'); secs = secs - 1; timerRunning = true;
} } //--> </script> </head>
<div id="tim"></div>
<script type="text/javascript"> InitializeTimer(); </script> </body>
|
|
See also
Do you have a Java Problem?
Java Books
Return to : Java Programming Hints and Tips All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
|