HAWKES08
HAWKES08

Reputation: 521

Select random function

I have a list of functions:

    function randomiseiconscycle1() {
    $("#iconTwoContainer img, #iconFiveContainer img, #iconSevenContainer img").fadeIn(300);
    setTimeout( function(){
        $("#iconTwoContainer img, #iconFiveContainer img, #iconSevenContainer img").fadeOut(300);
    },200);

function randomiseiconscycle2() {
    $("#iconOneContainer img, #iconSixContainer img").fadeIn(300);
    setTimeout( function(){
        $("#iconOneContainer img, #iconSixContainer img").fadeOut(300);
    },200);
}

everytime i click this button i have i want to activate one of the 8 functions (like above) randomly.

any help would be much appreicated.

Upvotes: 2

Views: 3448

Answers (5)

The Alpha
The Alpha

Reputation: 146201

Assumed that you have 2 functions i.e. randomiseiconscycle1 and randomiseiconscycle2

$(function(){

var totalfunc=2; // if more than 2 functions than increase the number.

function randomiseiconscycle1() {
    var name=arguments.callee.name;
    alert(name);
    setTimeout( function(){
        alert(name);
    },200);
}

function randomiseiconscycle2() {
    var name=arguments.callee.name;
    alert(name);
    setTimeout( function(){
        alert(name); 
    },200);
}    

$('button').on('click', function(){
    var randomnumber=Math.floor(Math.random()*totalfunc+(1));
    var func="randomiseiconscycle"+randomnumber;
    eval(func)();
});

});​

A fiddle is here.

Upvotes: 0

Guffa
Guffa

Reputation: 700362

Put references to the functions in an array:

var iconcycle = [
  randomiseiconscycle1, randomiseiconscycle2,
  randomiseiconscycle3, randomiseiconscycle4,
  randomiseiconscycle5, randomiseiconscycle6,
  randomiseiconscycle7, randomiseiconscycle8
];

Now you can pick one at random and call it:

iconcycle[Math.floor(Math.random() * iconcycle.length)]();

Upvotes: 8

slowBear
slowBear

Reputation: 263

You can create an array of functions, generate a random number and use that to call one of those functions:

http://jsfiddle.net/4PfAC/1/

Upvotes: 0

jbabey
jbabey

Reputation: 46647

in javascript functions are just objects, so you can do some fun things with them (such as selecting one at random)

This should be enough to get you started:

http://jsfiddle.net/jvGkp/

var arrayOfFuncs = [];

arrayOfFuncs.push(function () { alert('first func!'); });
arrayOfFuncs.push(function () { alert('second func!'); });
arrayOfFuncs.push(function () { alert('third func!'); });

arrayOfFuncs[0]();

Upvotes: 3

Shaded
Shaded

Reputation: 17836

I think you're looking for something like this...

function callRandomFunction() {
    var random = Math.floor(Math.random()*8);
    switch(random){
    case 0:
        randomiseiconscycle1();
        break;
    case 1:
        ....
    ...
    }
}

Upvotes: 0

Related Questions