mercredi 1 juillet 2015

Randomizing array elements and picking one in time interval with javascript

I have write piece of code that would randomly pick an element from array, and continiously looping the script in some interval. When I ran it, it works, but browser freeze, so its bad code. Its based on Fisher-Yates algorithm. Here is the code:

function random_notes(x){

    var frame = document.getElementById("frame");
    var my_array = ['E', 'G' , 'A', 'C', 'D', 'G#', 'F', 'C#', 'D#', 'A#', 'F#','B'];
    var ri = Math.floor(Math.random() * my_array.length);
    var result = my_array[ri];

    var div = document.getElementById('frame');
    div.innerHTML= result;

    setTimeout("random_notes()",x*1000); // x represent a seconds
    return random_notes();

}

and HTML

<input type= "submit" value= "submit" onSubmit="random_notes(2)">

Div with ID frame is defined in HTML also. Can you help me to optimize it? Thanks!




Aucun commentaire:

Enregistrer un commentaire