...

View Full Version : Implement setInterval() with "random array picker"



The Covenant
09-04-2010, 09:01 AM
Hi. I'm working on a script that picks out a random entry in an array every 10seconds and show it to the user (using document.write). So far I've got the "Randomizer" to work like this:



function random(){
var nummer = Math.floor(Math.random()* tekst.length);
return nummer;
}

var tekst = new Array("Different", "Values");


and showing it like this:



document.write(tekst[random()]);


Now, I've tried my best to implement setInterval() to give me a new random number every 10seconds, but so far without any luck...

I appreciate all help! :)

Thx in advance.

Philip M
09-04-2010, 09:17 AM
Use setTimeout()

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. 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.


All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

The Covenant
09-04-2010, 09:21 AM
Use setTimeout()

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. 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.


Okay. How do I show the result then?

Philip M
09-04-2010, 09:50 AM
Okay. How do I show the result then?

Use a <span>, e.g. <span id = "yourSpan">Something here</span>

Then in a script

document.getElementById("yourSpan").innerHTML = result;

There are lots of good examples of this sort of thing posted on this forum.
Have a look at http://www.codingforums.com/showthread.php?t=203899
Post #6.

Be aware that a random number generator such as you are attempting may well generate the same random number twice (or even three times) in succession, especially if the number of numbers is small. So the best approach is to shuffle the text array elements at the outset, and then display them in order 1,2,3,4 etc. This way you get no duplication.


Here is an example:


<span id = "q1"></span><br>

<script type = "text/javascript">

shuffle = function(v){
for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
}

var quotations = new Array();
quotations[0]= "germaine arnold"
quotations[1]= "endearing moral"
quotations[2]= "analog reminder"
quotations[3]= "regained normal"
quotations[4]= "renaming ordeal"
quotations[5]= "nominal regrade"
quotations[6]= "arraigned lemon"
quotations[7]= "ringleader moan"
quotations[8]= "mineral groaned"
var shf = shuffle(quotations);

var index = 0;
function show() {
document.getElementById("q1").innerHTML = quotations[index];
index ++;
if (index > 8) {index = 0} // start again with same sequence of quotations
//if (index > 8) {index = 0; shuffle(quotations)} // re-shuffle quotations into a new sequence and start again
setTimeout("show()",10000); // 10 seconds delay
}

show();

</script>

The Covenant
09-04-2010, 10:20 AM
Use a <span>, e.g. <span id = "yourSpan">Something here</span>

Then in a script

document.getElementById("yourSpan").innerHTML = result;

There are lots of good examples of this sort of thing posted on this forum.
Have a look at http://www.codingforums.com/showthread.php?t=203899
Post #6.

Well. I looked at the link you gave me, but it didn't help me that much... I'm very new in this JavaScript world.

But, do I write it like this?



document.getElementById("id of my <p>").innerHTML = tekst[random()];

Philip M
09-04-2010, 10:28 AM
Well. I looked at the link you gave me, but it didn't help me that much... I'm very new in this JavaScript world.

But, do I write it like this?



document.getElementById("id of my <p>").innerHTML = tekst[random()];


Oh, sorry I spoke! :p If you cannot learn from the examples given you would perhaps be best to give up JavaScript and take up underwater motorcycling instead. :D:D

var nummer = Math.floor(Math.random()* tekst.length);
document.getElementById("id of my <p>").innerHTML = tekst[nummer];

The Covenant
09-04-2010, 10:34 AM
Oh, sorry I spoke! :p If you cannot learn from the examples given you would perhaps be best to give up JavaScript and take up underwater motorcycling instead. :D:D

var nummer = Math.floor(Math.random()* tekst.length);
document.getElementById("id of my <p>").innerHTML = tekst[nummer];

Hehe... I'm trying here...!:o But nothing happens when I write it like this...:(

gusblake
09-04-2010, 11:25 AM
When does the script run? If it's called in the head or above the <p>, the <p> won't exist at the time of execution.

If you look in the error console you might find something like
document.getElementById("id of p") is null or not an object

Philip M
09-04-2010, 11:25 AM
Hehe... I'm trying here...!:o But nothing happens when I write it like this...:(

document.getElementById("id of my <p>").innerHTML = tekst[nummer];

The id must of course be the actual id. And the <p> must exist at the time the script is executed.

Why not simply use the examples you were provided with?

The Covenant
09-04-2010, 11:43 AM
document.getElementById("id of my <p>").innerHTML = tekst[nummer];

The id must of course be the actual id. And the <p> must exist at the time the script is executed.

Why not simply use the examples you were provided with?

but of course! still didn't work... but i guess I'll just have to try until I get it right...:(

Sciliano
09-04-2010, 11:57 AM
Covenant:

Using my code from here:
http://codingforums.com/showpost.php?p=990006&postcount=6 which was cited by Philip M, I inserted Philip M's array randomization code from here:
http://codingforums.com/showpost.php?p=946122&postcount=7

Just copy the entire post, save it as an .html document, then open that document in your browser.

What more do you expect someone to do? Make an effort to help yourself.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>None</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">

var rotate = "";
var nMessage = 0;

function rotateMessage(messageContainer,rotateDelay,messages){

messageContainer.firstChild.data = messages[nMessage];
nMessage = nMessage == messages.length-1 ? 0 : nMessage + 1;
rotate = setTimeout
(
function()
{
rotateMessage(messageContainer,rotateDelay,messages)
}
, rotateDelay * 1000
);
}

function randOrd(){

return (Math.round(Math.random())-0.5);
}

function init(){

var rotateDelay = 3; // 3 seconds;
var randomize = true; // or false;

var messages = [];
var nDiv = document.getElementsByTagName('div');
for (i=0; i<nDiv.length; i++)
{
if (nDiv[i].className == "message_display")
{
var messageContainer = nDiv[i];
var nItems = nDiv[i].getElementsByTagName('ul')[0].getElementsByTagName('li');
for (n=0; n<nItems.length; n++)
{
messages[messages.length] = nItems[n].firstChild.data;
}
}
}
while(messageContainer.lastChild)
{
messageContainer.removeChild(messageContainer.lastChild);
}
if (randomize)
{
messages.sort(randOrd);
}
messageContainer.appendChild(document.createTextNode(' '));
messageContainer.onmouseover = function()
{
this.style.cursor = "wait";
clearTimeout(rotate);
this.onmouseout = function()
{
this.style.cursor = "default";
rotate = setTimeout
(
function()
{
rotateMessage(messageContainer,rotateDelay,messages)
}
, rotateDelay * 1000 * .25
);
}
}
rotateMessage(messageContainer,rotateDelay,messages)
}

navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);

</script>
<style type="text/css">

body {background-color: #fffacd; margin-top: 60px;}
.message_display {width: 500px; border: 1px solid black; text-align: center;
font-family: tahoma; font-size: 12pt; background-color: #eee8aa;
font-weight: bold; padding: 3px; margin: auto; cursor: default;}
.message_display ul {margin: 0px;}

</style>
</head>
<body>

<div class="message_display">
<ul>
<li>This is the first message</li>
<li>This is the second message</li>
<li>This is the third message</li>
<li>This is the fourth message</li>
<li>This is the fifth message</li>
</ul>
</div>

</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum