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.
CodePudding user response:
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)
CodePudding user response:
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.
html
...
<body>
...
<p id="random-thing"> </p>
...
</body>
...
js
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);