I have a web page where I display a quote. I pick one of the quotes at random. At the moment it does this every time the web page is loaded, I would now prefer that it picks one every 5 seconds. I’m a beginner and not sure how best to implement this nor the appropriate function. setInterval
?, setTimeout
?, delay
?, wait
?
var quotes = JSON.parse('{
"0": "Don't worry about what anybody else is going to do. The best way to predict the future is to invent it. -- Alan Kay",
"1": "Keep away from people who try to belittle your ambitions. Small people always do that, but the really great make you feel that you, too, can become great. -- Mark Twain",
"2": "No problem should ever have to be solved twice. -- Eric S. Raymond, How to become a hacker",
"3": "Attitude is no substitute for competence. -- Eric S. Raymond, How to become a hacker",
"4": "It is said that the real winner is the one who lives in today but able to see tomorrow. -- Juan Meng",
"5": "Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it. -- Alan J.Perlis(Epigrams in programming)",
"6": "A year spent in artificial intelligence is enough to make one believe in God. -- Alan J.Perlis(Epigrams in programming)"
}');
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
var num = Math.floor(getRandomArbitrary(0, Object.keys(quotes).length));
document.getElementById('quote').innerHTML = quotes[num];
As mentioned I would now like the value in ID 'quote'
to be updated every 5 seconds. So I would assume that means updating the num
var?
3
Answers
You can indeed use setInterval to accomplish this. Try adding a setInterval like so:
The second parameter of setInterval accepts number of milliseconds, so in your case this is 5000. Read more here
You can use setInterval which repeatedly calls a function or executes a code snippet, with a fixed time delay & inside the callback function get a new
num
every time.@shmink, It is good that you have come up with code to populate a div, I have added a snippet to call that in setInterval which updates every 5s. Make sure you call clearInterval to stop the setInterval once you move away(Move to some other page, close).