-1

I found this code here on Stackoverflow which displays random words onpage load and shows a new one when one reloads page. Being new to Javascript, i do not know how to make it loop between the words once page loads. That is displaying a new word from the list after every one second.

The Code is

var things = ['Rock', 'Paper', 'Scissor'];
var thing = things[Math.floor(Math.random()*things.length)];
alert('The computer chose:' + thing);

EDIT: I would like to be priting the result on the page and not using alert.

Steven Helson
  • 65
  • 2
  • 10
  • "make it loop" this is exactly the term you should be searching for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration – Benjamin Gruenbaum Mar 21 '22 at 12:41
  • 2
    @BenjaminGruenbaum [`setInterval`](//developer.mozilla.org/en/docs/Web/API/setInterval) is more relevant here. – Sebastian Simon Mar 21 '22 at 12:41
  • What exactly do you mean by _“loop between the words”_? Can you [edit] your question and show some example output? Other than that, see [Call a Javascript function every 5 seconds continuously](/q/7188145/4642212) and [Prevent alert() from halting the execution of JavaScript](/q/33203157/4642212). – Sebastian Simon Mar 21 '22 at 12:42
  • But you don't want to repeatedly "loop and alert" with `setInterval` otherwise you'll be there all day closing down alerts. – Andy Mar 21 '22 at 12:43
  • @Andy i won't be using the alert, i will rather be printing on the page – Steven Helson Mar 21 '22 at 12:44
  • It's probably worth pointing out that using that code you might get 20 "paper" in a row because of how the random number is generated. – Andy Mar 21 '22 at 12:53
  • @Andy what would be the best way to fix that? – Steven Helson Mar 21 '22 at 12:56
  • @StevenHelson Just create an inner loop, and keep calling Random() until your new value is different to your last value (create a second variable to hold that value.) – MikeB Mar 21 '22 at 16:40

3 Answers3

1

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>
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Thanks for the answer. Wanted to ask if it is possible to put the result in a variable rather that logging into console? – Steven Helson Mar 21 '22 at 14:25
  • You want to log the result as textContent of an element? – Andy Mar 21 '22 at 14:30
  • Yes Exactly. I want to log the result as textContent of an element. – Steven Helson Mar 21 '22 at 14:31
  • 1
    Answer updated! @StevenHelson. Just cache the element, and pass it in as an argument. That way you're not hitting the DOM on every iteration which is better for performance. – Andy Mar 21 '22 at 14:33
0

What you are looking for is setInterval()

const things = ['Rock', 'Paper', 'Scissor'];

setInterval(function() {
   const thing = things[Math.floor(Math.random()*things.length)];
   console.log('The computer chose : ' + thing);
}, 1000)
Selin Jodhani
  • 16
  • 1
  • 3
0

Correct answer to your question requires knowledge of two things. setInterval and document query selectors. To answer you in the most simple way possible I have divided solution to HTML and JS codes. In the HTML section you can see the DOM Element "p". It has ID called "random-thing". In CSS We refer to it, as #random-thing.

JavaScript code selects this element (Warning, it can be null, that's why we want to check whether it exists.). Then we can change element's property called innerText. You could also change it using innerHTML, but because we only want to change the text content, let's use the innerText property.

  const randomThingDomEl = document.getElementById("random-thing");
  const things = ['Rock', 'Paper', 'Scissor'];
  const getRandomThing = () => things[Math.floor(Math.random()*things.length)];

  setInterval(() => {
   if (randomThingDomEl) {
    randomThingDomEl.innerText = getRandomThing();
   }
  }, 1000);
<p id="random-thing" />