Random Image shuffle Javascript code Thursday, Apr 21 2011 

I tested the script and it’s perfect, only thing is I need the random images to load within a set table/cell. The ” onload=”ShufImages();” function needs to be confined within a set table/cell.

I’ve tried placing the function in the header but it errors.

Any help would be greatly appreciated.

Thanks in advanced.

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
http://www.w3.org/TR/html4/strict.dtd”&gt;
<html>
<head>
<title></title>
<script language=”JavaScript” type=”text/javascript”>
<!–
var ImgPath=’/StdImages/’;
var ImgAry=new Array(‘One.gif’,’Two.gif’,’Three.gif’,’Four.gif’,’Five.gif’);
var RandomNu;
var ImgCnt=1;
function ShufImages(){
while (ImgCnt<ImgAry.length){
RandomNu=Math.floor(Math.random()*(ImgAry.length-1));
if (ImgAry[RandomNu]!=’X’){
document.getElementById(‘I’+ImgCnt).src=ImgPath+ImgAry[RandomNu];
ImgAry[RandomNu]=’X’;
ImgCnt++;
}
}
}
//–>
</script>
</head>
<body onload=”ShufImages();” >
<table width=”400″ border=”1″ >
<tr>
<td>
<img id=”I1″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
<td>
<img id=”I2″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
<td>
<img id=”I3″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
<td>
<img id=”I4″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
</body>
</html>
Advertisements

Very simple example of Javascript sleep method Tuesday, Apr 12 2011 

Have you ever needed the sleep command in JavaScript? Usually you can use the existing setTimeout(), clearTimeout() and setInterval() to accomplish what you want and in those cases you should use the native functions. But if you really need the sleep or wait statement lets go through the options and see what code might work the best.

JavaScript sleep by loop

<script type="text/javascript">
// bad implementation
function sleep(milliSeconds){
	var startTime = new Date().getTime(); // get the current time
	while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
</script>
We are using a while loop on line 3 that continually
 evaluates the current time against the time when
 we should stop blocking. This loop will run as fast
 as the browser will let it all the while using up 
valuable cpu resources. Checking the time might not 
seem like much but doing it thousands (or tens of thousands) 
of times per second make a noticeable performance impact 
on your computer (try it and watch your cpu meter). 
This code will "pause" your thread but will also use
 all the resources your computer will give it.
Resource taken from:
http://www.devcheater.com/