Tuesday, May 4, 2010

# Display random number in random way using JavaScript

1:33 AM
I think you guys already know about how to get the random number using JavaScript, if you don’t know then you can use Math.random() to display a random no ranging from 0 to 1. It would have been better if we display the random number in the random way using JavaScript. Ok, Let’s do it..

Displaying random number in the random way
To display random number in the random way, what we need is get the random number and write the random in a certain interval.
HTML Code :
<div id='random'>0.00</div>
<input name="button" type="button" value="Click Me" onClick="randValue(40,5)" />

As you can see above, the “div” with id “random” gets updated within specified interval and when button is clicked it call the JavaScript function “randValue()”. The first parameter is the maximum of the random number and second parameter specifies how many times the action should be repeated to show the final random number.
JavaScript Code :
<script>
var i=1; //counter
function randValue(maxVal,no_of_time)
{
i++; //counter increment
//get a random no upto maxVal and round it to two decimal place
var theNumber = (Math.random()*parseInt(maxVal)).toFixed(2);
//put the number to that
document.getElementById('random').innerHTML=theNumber; //gett
if(i<=no_of_time)
setTimeout("randvalue("+maxVal+","+no_of_time+")",300);
else
i=1;
}
</script>

As you can see in the first line, counter is set to 1. In the first line of the function, counter is incremented. And then, the content of the “div” is made blank.
var theNumber = (Math.random()*parseInt(maxVal)).toFixed(2);

As you can in this line, the random no is multiplied with the supplied argument to get the random number between zero to maxVal since Math.random() only returns the random number between 0 to 1. And, “toFixed(2)” expression rounds the number to two decimal places. And that number is placed in the “div”.And then “setTimeout()” calls the same function in every 300 millisecond until the counter reaches to “no_of_time”. And, finally the counter is set to 1 to iterate through the same action.