Because you only have a small set of items you want to loop over, and are trying to prevent the same "random" item from being written lots of times in a row, you'll have to implement some sort of "remembering" system. Here I make a copy of the array and splice
words from it, and then reset it once it's empty.
I've also used setTimeout
in this example. (Personal preference.) You'll still occasionally get the same word come up twice in a row as the array resets. If you wanted no repeated words you can build that check into the function, but I think that defeats the whole purpose of "rock, paper, scissors" - sometimes you want to play "paper" 20 times in a row :)
const arr = ['Rock', 'Paper', 'Scissor'];
const el = document.querySelector('#demo');
// `log` accepts and array of words, and an element
function log(arr, el) {
// Makes a copy of that array
let copy = [...arr];
// Main loop that `setTimeout` calls over and over...
function loop() {
// Get the random number
const rnd = Math.floor(Math.random() * copy.length);
// Get a word by `splicing` it out of the array copy
const word = copy.splice(rnd, 1);
// Updated the element text content
el.textContent = `The computer chose: ${word}`;
// If there are no words left in the copy, reset it
if (!copy.length) copy = [...arr];
// Call `loop` again
setTimeout(loop, 1000);
}
// Call `loop`
loop();
}
log(arr, el);
<div id="demo"></div>