PDA

View Full Version : Need help with counter in javascript



Columbo
08-13-2009, 05:24 AM
Let me state right off the top that I know nothing about javascript.

I am trying to display a single string that says "Record has been added sucessfully" in a table and then have it display for about 5 seconds. After the 5 seconds is up, it will then redirect to another page.

Since I am working with a test file, it does not actually redirect, but simply displays the word "Done!" when the 5 seconds is up instead.

The problem I am having is that it seems to be running in reverse. It seems that the counter executes first and then when the time is up, it displays the word "Done" and finally displays the table with the string "Record has been added sucessfully" right below it.
The code that I am using is:



<html>
<head>
<title>Timed Display</title>
</head>
<body>
<center>
<table width="300px" height="100" style="border: 1px solid #000000;">
<tr><td align="center">
<script langage="javascript">
<!--
document.write("Record has been added sucessfully");
-->
</script>
</td></tr>
</center>
<script language="javascript">
<!--
var timer=0;
for (count=1; count<=5000; count++){
timer=count; /* I don't need this but examples I looked at had something in here. */
}
document.write("Done!");
-->
</script>
<body>
<html>


Can anyone explain to me why it is working this way and how to achieve the intended goal?

Thanks

vwphillips
08-13-2009, 08:46 AM
document.write can only be used as the page loads



<html>
<head>
<title>Timed Display</title>
</head>
<body>
<center>
<table width="300px" height="100" style="border: 1px solid #000000;">
<tr><td align="center">
<script langage="javascript">
<!--
document.write("Record has been added sucessfully");
-->
</script>
</td></tr>
</center>
<script language="javascript">
<!--

var timer=new Date();
function Timer(){
if (new Date()-timer<5000) setTimeout(function(){ Timer(); },10);
else alert('Done');
}

Timer();
-->
</script>
<body>
<html>

Columbo
08-13-2009, 02:54 PM
Thank you very much for your help. It is not the date that I want to count down but I think that I can play around with it a bit to get it to simply pause the page display for 5 seconds before redirecting to the other page.

Thanks again. Very much appreciated.