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]



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);
1000); // every 1 second

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);

Others have answered the question, but just for the fun of it, here is a visual dice throwing example, using the Math.random javascript method, a background image and some recursive timeouts.


function rollDice(){
   return (Math.floor(Math.random()*6)+1);

Javascript has a random() available. Take a look at Math.random().


Coding in Perl, I used the rand() function that generates the number at random and wanted only 1, 2, or 3 to be randomly selected. Due to Perl printing out the number one when doing "1 + " ... so I also did a if else statement that if the number generated zero, run the function again, and it works like a charm.

printing out the results will always give a random number of either 1, 2, or 3.

That is just another idea and sure people will say that is newbie stuff but at the same time, I am a newbie but it works. My issue was when printing out my stuff, it kept spitting out that 1 being used to start at 1 and not zero for indexing.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.