0
\$\begingroup\$

Can anyone review this?

setInterval(function() {
var days_array = [31,29,31,30,31,30,31,31,30,31,30,31];
var m = randNum(12);
var m_limit = days_array[m-1];
var d = randNum(m_limit);
$("code").html("day = "+d+"<br>month = "+m);
},1000);
function randNum(limit){var r=Math.floor(Math.random()*limit)+1;return r;}

jsFiddle

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 24, 2012 at 9:01
\$\endgroup\$

4 Answers 4

3
\$\begingroup\$
function randomMillisecond()
{
 return Math.floor(Math.random() * 1000 * 60 * 60 * 24 * 365.25);
}
setInterval(function() {
 var date = new Date(randomMillisecond());
 $("code").html("day = " + date.getDate() + "<br>month = " + date.getMonth());
}, 1000);

If you don't need 02/29.

answered Aug 24, 2012 at 20:59
\$\endgroup\$
3
\$\begingroup\$
function randNum(limit){var r=Math.floor(Math.random()*limit)+1;return r;}

Can be shortened to:

function randNum(limit){return Math.floor(Math.random()*limit)+1;}

You should also declare your variables outside of the setInterval and then set them inside only if you need to (for example, the days_array never changes so only needs to be decalared once and not every second.

answered Aug 24, 2012 at 10:00
\$\endgroup\$
0
3
\$\begingroup\$

This is biased towards days in shorter months. If you want every day to be equally likely you should choose a random number from 1 to 365 (366 for leap years) and calculate the day and month from that.

answered Aug 24, 2012 at 18:17
\$\endgroup\$
0
\$\begingroup\$

I would reduce the visibility of the variables so they won't get overwritten by accident and I'd separate the date creation from displaying them. Like this, for example:

var datePasser = function(callback) {
 var randNum = function(max) {
 return Math.floor(1 + Math.random() * max);
 },
 daysInMonth = [31,29,31,30,31,30,31,31,30,31,30,31];
 return function() {
 var month = randNum(12),
 date = randNum(daysInMonth[month - 1]);
 callback(month, date);
 }
 },
 printRandomDate = datePasser(function(month, date) {
 $('code').html("day = "+date+"<br>month = "+month);
 });
setInterval(printRandomDate, 1000);​
answered Aug 24, 2012 at 16:07
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.