1

I want these messages to randomly display, but none repeat, till it's gone through them all. Why are some messages getting skipped or I'm getting 'undefined' returned?

var ranNums = [],
    container = $('#container'),
    messages = [
    'message 1',
    'message 2',
    'message 3',
    'message 4'
  ],
  totalMessages = messages.length;

function waitForNext() {
setTimeout(function(){
  changeMsg();
}, 1000);
}

function getNewRanNum() {
var num = Math.floor(Math.random() * totalMessages);

  if(ranNums.indexOf(num) > -1) {
  getNewRanNum();
  return;
} else {
  ranNums.push(num);
  console.log(num, ranNums);
  return num;
}
}

function changeMsg() {
var newMsg = getNewRanNum();

container.append(messages[newMsg] + '<br>');

if (ranNums.length === totalMessages) {
  console.log('end');
  return false;
}

waitForNext();
}

changeMsg();
zebapy
  • 643
  • 1
  • 5
  • 21
  • 1
    XY-problem strikes again. Did you ever consider making an array with each of your items in it, then shuffling the array using fisher-yates algorithm? Your "GetAnother" style is probably somewhat biased and definitely inefficient. In extreme situations, you could even blow the recursion stack. Implement this: http://stackoverflow.com/a/2450976/14357 – spender May 14 '14 at 23:41

2 Answers2

3

Your getNewRanNum function in certain conditions will return: num and in other cases will return undefined (with the return; statement). If your aiming to call recursively, it needs to return the num of the final recursive call. Something like this

function getNewRanNum() {
var num = Math.floor(Math.random() * totalMessages);    
  if(ranNums.indexOf(num) > -1) {
      return getNewRanNum();
   } else {
      ranNums.push(num);
      console.log(num, ranNums);
      return num;
   }
}
OJay
  • 4,763
  • 3
  • 26
  • 47
  • An easier solution might be to remove a message from the array after it has been selected, then select from the new array of messages, but this works nonetheless. – tomysshadow May 15 '14 at 00:37
0

Here's your problem:

if(ranNums.indexOf(num) > -1) {
  getNewRanNum();
  return;
}

You're getting a new random number, but you're not returning it. Instead, try:

if(ranNums.indexOf(num) > -1) {
  return getNewRanNum();
}

Check out this jsfiddle.

Kylok
  • 767
  • 6
  • 15