Search code examples
javascriptrandomiterationshuffle

How to make a for loop that will go through functions without going through the same one twice


I have some functions, like:

function functionOne() {
    /*
    code
    */
}
function functionTwo() {
    /*
    code
    */
}
function functionThree() {
    /*
    code
    */
}

How can I write code to call each of the functions, once each (i.e. without repeats), in a random order?


Solution

  • Put your functions in an array, randomise the array and then iterate through it:

    var functions = [
    function () {  alert("function 0");  },
    function () {  alert("function 1");  },
    function () {  alert("function 2");  },
    function () {  alert("function 3");  },
    function () {  alert("function 4");  }
        ];
    
    functions.sort(function() { return 0.5 - Math.random() });
    
    for (var i=0;i<5;i++) {
        console.log(i);
        functions[i]();
    }
    

    Here's a fiddle