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

\$\endgroup\$
1
\$\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.

|improve this answer|||||
\$\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.

|improve this answer|||||
\$\endgroup\$
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.

|improve this answer|||||
\$\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);​
|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.