1

I have made a slideshow which shows exactly a random slogan, but when I check in the console, some of the slogans will be repeated twice of even three times. That is exactly what I want to avoid, but how can I implement that into my codes below.

    setInterval("insertText()", 9000);

    function insertText() {
        var i = Math.floor(slogan.length * Math.random());
        var text = document.getElementById("textinsidebox");
        var sloganInfo = "<img src=" + slogan[i].image + " id='img_slogan'>" + "<br>" + slogan[i].text + "<br>" + slogan[i].person;
        text.innerHTML = sloganInfo;
    }
  • You will have to remove printed slogans from array – Rajesh Nov 11 '16 at 11:07
  • 1
    http://stackoverflow.com/questions/6625551/math-random-number-without-repeating-a-previous-number – Samuil Petrov Nov 11 '16 at 11:08
  • What did you check in the console? there is nothing printed in there. Also what do you wish to happen when you run out of slogans? – Tamas Hegedus Nov 11 '16 at 11:09
  • I think he expects that the script displays slogans randomly and repeatedly but he wonders why some are shown twice. Related read: http://stackoverflow.com/questions/12673691/true-or-better-random-numbers-with-javascript. –  Nov 11 '16 at 11:10

1 Answers1

0

You could use an own property of the function to store the last value.

function insertText() {
    var i;
    do {
        i = Math.floor(array.length * Math.random());
    } while (i === insertText.i);
    console.log(insertText.i, i);
    insertText.i = i;
}

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
setInterval(insertText, 500);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392