How do I make a random shuffle?

How to make video playback very random? (right now it's playing after French, Dutch and after Nederlands, French, but I want to randomly shuffle out of those two)

var playing ='FR';
function video_idle() {
    $('#mediaplayer').attr('src',playing + '.mp4' ).show(); 
    mediaplay_video= document.getElementById('mediaplayer');  
    mediaplay_video.play();  
    mediaplay_video.onended = function(e) {
      console.log('>>> Playing finished: ', e);
      if(playing ==='FR') {
        playing='NL';
        video_idle();
      } else {
        playing='FR';
        video_idle();
      }      
    };   
}

      

+3


source to share


2 answers


To pick a random video, just put all possible languages ​​into an array and pick one at random:

var languages = ['FR', 'NL'];
var playing = 'FR';
function video_idle() {
    $('#mediaplayer').attr('src',playing + '.mp4' ).show();
    mediaplay_video= document.getElementById('mediaplayer');
    mediaplay_video.play();
    mediaplay_video.onended = function(e) {
        console.log('>>> Playing finished: ', e);

        playing = languages[Math.floor(languages.length * Math.rand())];
        video_idle();
    };
}

      



languages.length * Math.rand()

gives you a random float value between 0 and the length of your array, then Math.floor()

rounds it up so that you end up with a random integer between 0 length-1

and which is your array-keys.

+1


source


Assuming you only want to shuffle between the two possible languages, you can use Math.round(Math.random())

which will give you a value of 0 and 1 (which in JavaScript will check for true or false):

var playing ='FR';
function video_idle() {
    $('#mediaplayer').attr('src',playing + '.mp4' ).show(); 
    mediaplay_video= document.getElementById('mediaplayer');  
    mediaplay_video.play();  
    mediaplay_video.onended = function(e) {
      console.log('>>> Playing finished: ', e);
      if(Math.round(Math.random())) {
        playing='NL';
        video_idle();
      } else {
        playing='FR';
        video_idle();
      }      
    };   
}

      



If you have more languages ​​or expect more languages ​​then you will need to consider the solution suggested by @Lars Ebert.

+2


source







All Articles