Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomize numbers with jQuery?

Is there a simple jQuery way to create numbers randomly showing then a number 1 -6 is choosing after a few seconds? [Like dice]

like image 700
omnix Avatar asked Nov 29 '10 17:11

omnix


People also ask

How do you randomize JavaScript?

Generating Javascript Random Numbers Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.

How do you get a random number between two numbers in JavaScript?

Example: Integer Value Between Two Numbers In JavaScript, you can generate a random number with the Math. random() function. The above program will show an integer output between min (inclusive) to max (inclusive). First, the minimum and maximum values are taken as input from the user.

What is math random in JavaScript?

JavaScript Math random() Method random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range. Syntax : Math.


2 Answers

This doesn't require jQuery. The JavaScript Math.random function returns a random number between 0 and 1, so if you want a number between 1 and 6, you can do:

var number = 1 + Math.floor(Math.random() * 6); 

Update: (as per comment) If you want to display a random number that changes every so often, you can use setInterval to create a timer:

setInterval(function() {   var number = 1 + Math.floor(Math.random() * 6);   $('#my_div').text(number); }, 1000); // every 1 second 
like image 138
casablanca Avatar answered Oct 04 '22 07:10

casablanca


You don't need jQuery, just use javascript's Math.random function.

edit: If you want to have a number from 1 to 6 show randomly every second, you can do something like this:

<span id="number"></span>  <script language="javascript">   function generate() {     $('#number').text(Math.floor(Math.random() * 6) + 1);   }   setInterval(generate, 1000); </script> 
like image 44
cambraca Avatar answered Oct 04 '22 06:10

cambraca