...

View Full Version : Why can't my program be random!



wylie233
07-21-2012, 04:03 PM
Hello!


i have a problem, which is i can not get this code right:






<html>
<head>
<script type = "text/javascript">

var body2 = document.getElementById("body2");
var talk_sen = ["", "did","do", "not"];
var ran_talk_sen = talk_sen[Math.floor(Math.random() * talk_sen.length)];


setInterval(function(){document.write(ran_talk_sen)},3000);

</script>
</head>
<body>






</body>

</html>










SO the idea is, every 3 seconds if prints out a random element of the array, this does not quite work because
it only prints out 'do' then after 3 secs it prints 'do' etc, until my page says dodododododododododododododododododo.

i am hoping for diddonotnotnotdiddodidnotdodonotdiddid - or something random like that!



Thanks!!!

vwphillips
07-21-2012, 04:50 PM
<body>
<html>
<head>
document.write can not be used after the page has loaded
<div id="body2" ></div>
<script type = "text/javascript">

var body2 = document.getElementById("body2");
var talk_sen = ["", "did","do", "not"];
var ran_talk_sen = talk_sen[Math.floor(Math.random() * talk_sen.length)];


setInterval(function(){ body2.innerHTML=talk_sen[Math.floor(Math.random() * talk_sen.length)]; },3000);

</script>
</head>
<body>

Philip M
07-21-2012, 05:02 PM
Seems a bit pointless, but I expect it is homework.

document.write() is in effect obsolete. document.write() statements must be run before the page finishes loading. Any document.write() statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page (including the Javascript which called it). So document.write() is at best really only useful to write the original content of your page. It cannot be used to update the content of your page after that page has loaded.

So you must use DOM methods to display the result.


<body onload ="myfunc()">
<div id = "result"></div>
<script type = "text/javascript">
function myfunc() {
var talk_sen = ["", "did","do", "not"];
var ran_talk_sen = talk_sen[Math.floor(Math.random() * talk_sen.length)];
document.getElementById("result").innerHTML += ran_talk_sen + "<br>";
setTimeout(myfunc,2000);
}
</script>

But you have no way of bringing it to an end!

wylie233
07-22-2012, 01:19 PM
Thanks! Yes my example is pointless, but i am using the same method for something else!

Document.write does clear the page - i know this, but it was just to do a quick check for if it worked!!

Thanks again!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum