-1

If I have these functions defined:

function playZoomout() {
// do things
}
function playZoomin() {
// do things
}
function playPanright() {
// do things
}
function playPanleft() {
// do things
}

and am running this every four seconds:

var timer = setInterval(playZoomout,4000);

How can I replace "playZoomout" with a randomly selected function picked from the ones defined above? I'm looking for a jQuery or plain javascript solution.

kthornbloom
  • 3,660
  • 2
  • 31
  • 46
  • 1
    Put the functions in an array and [pick a random element from that array](http://stackoverflow.com/q/4550505/218196). – Felix Kling Sep 23 '13 at 15:27

3 Answers3

3

Create an array of function references, then fetch an element randomly from the array and invoke it.

var fns = [playZoomout, playZoomin, playPanright, playPanleft]
setInterval(function () {
    fns[Math.floor(Math.random() * fns.length)]();
}, 1000)

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Perhaps calling `fn()` on a separate line is more readable, but you can also do `fn[Math.floor(Math.random() * fns.length)]();` without using an unnecessary variable. – Bucket Sep 23 '13 at 15:28
  • This answers the question! Just wondering- How would I clear this interval? – kthornbloom Sep 23 '13 at 20:30
0

Add each functionname to an array, with numerical key indexing. Then, randomly generate a number between the lower and upper index and use a control structure to repeat the process.

Charles D Pantoga
  • 4,307
  • 1
  • 15
  • 14
0

Something like this should work (see http://jsfiddle.net/w6sdc/):

/* A few functions */
var a = function() {
    alert("A");
}

var b = function() {
    alert("B");
}

var c = function() {
    alert("C");
}

/* Add the functions to an array */
var funcs = [a, b, c];

/* Select a random array index */
var i = Math.floor(Math.random() * 2) + 0;

/* Call the function at that index */
funcs[i]();

Wrapping the index selection and the function call in a setInterval should be straight forward from this point.

Julio
  • 2,261
  • 4
  • 30
  • 56