PDA

View Full Version : Trouble with timeout/while loop


Morf
04-06-2006, 09:00 PM
Hello.

I'm trying to decrease my numeric variable in random increments from 0-4 every 5 seconds until this variable reaches 0. Basically it's a countdown, but has a random increment each count. Here's my code:




var position=Math.round(Math.random()*5000)

while (position < 4900)
{

position=Math.round(Math.random()*5000)

}

setTimeout ( "document.write(position)", 3000 );


While (position > 1)
{
var increment=Math.round(Math.random()*4);

position==(position-increment)

setTimeout ( "document.write(position)", 5000 );
}


Does anyone know why it is not working? It displays the first number generated after 3 seconds, and it is a number between 4900 and 5000, as intended, but does not change from there. Thanks for your help.

Thompson
04-06-2006, 09:42 PM
what exactly you want to do with this program?

iīve tested and debugged here, the program enters in the first while and stay there for a long time, and after this, it execute the setTimeout.

but, the setTimeou didnīt work... a javascript error was prompted "Object necessary near line 13"

maybe iīm not understanding the objective of this, but, for me, it makes no sense. the setTimeout is inside the "while", shoud it not be out of the while??

another thing...

"position==(position-increment)"

this instruction should be used inside an if. implemented like this, it says nothing to the program. i think you wanted to say "position = position-increment;", isnīt it??

if there someone here that understood the goal of this program, post it!
iīm curious about it :D

thelinuxduck
04-06-2006, 10:17 PM
I'm not sure what you're trying to do either, but here's a working example which starts with a number between 4900 and 5000, decreases from 1-4 randomly, and displays the output every 5 seconds:

<head>
<script>
var startnum = parseInt((Math.random() * 100) + 4901);
var currentnum = startnum;

function doNumbers() {
showNumber();
setTimeout('decreaseNum()', 5000);
}

function decreaseNum() {
currentnum -= parseInt((Math.random() * 4) + 1)
showNumber();
setTimeout('decreaseNum()', 5000);
}

function showNumber() {
document.body.appendChild(document.createTextNode(currentnum));
document.body.appendChild(document.createElement('BR'));
}

</script>
</head>
</html>
<body onload="doNumbers();">
</body>
</html>

felgall
04-06-2006, 11:28 PM
A case of the document.write overwriting the entire page after the page has finished loading so that there is no code there to run for the second time through.

Morf
04-07-2006, 03:33 AM
I found the solution, thanks all for your help!

Thompson
04-08-2006, 03:35 AM
hey, wait!

show us your solution. share the knowledge with all!! :D