Countdown with JavaScript –How remember the state?

Hi everyone,

I need 100-120 sec delay on my web page. I found a countdown script –attached, which works fine. The problem with this script is, that when you leave the page and then come back it starts countdown all over again. I need the counter refresh itself only if you close the browser otherwise it must remember its state. How can I do this with JavaScript, PHP and HTML? Any suggestions?

<html>
<head>
....
<script language="javascript">
function afterDelay() {
....
}
</script> 
</head>

<body>

<form name="redirect">
You will be redirected in
<input  type="text" size="1" name="redirect2">
</form>
seconds

<script type="text/javascript">
<!--
var countdownfrom=5 
var currentsecond=document.redirect.redirect2.value=countdownfrom+1
function countredirect(){
if (currentsecond!=0){
currentsecond-=1
document.redirect.redirect2.value=currentsecond
}
else{
afterDelay()
return
}
setTimeout("countredirect()",1000)
}
countredirect()
//-->
</script> 			
</body>
</html>

Using PHP you can make use of sessions, but what might be more reliable could be cookies.
Here are some useful cookie-handling functions that help to make managing them easier.

I’m aware about the concept generally, but I need something more specific. Thanks though.

More specific, such as this?

Instead of storing a countdown value, it can be better to store the time/date when the countdown period will be reached.

That way, when loading the page, you can attempt to read that countdown time/date.
If no prior countdown time exists, set it to what it should be, and save it out to a cookie.

Then you can calculate the current countdown value by taking the difference between that time/date value, and the time/date of what it is right now.

Thanks again, Paul. Can you express your ideas in code examples? Because I’ve tried already a few things but no success so far. Here is one of the ideas:

I tried to save and then pass currentsecond value from JavaScript to PHP and then back to JavaScript again. See the code below:

<script type="text/javascript">
<!--
var countdownfrom=
<?php
$delay=120;
$currentsecond= $_GET['currentsecond'];
if ($currentsecond < $delay-1){echo $currentsecond;}
else {echo $delay;}
?>
var currentsecond=document.redirect.redirect2.value=countdownfrom+1
function countredirect(){
if (currentsecond!=0){
currentsecond-=1

document.location.href='<?php echo $PHP_SELF . "?currentsecond="; ?> currentsecond'
document.redirect.redirect2.value=currentsecond
}
else{
afterDelay()
return
}