I've been trying to show a random quote in my webpage with jQuery. But the while(true) { } approach did not solve my problem, and yet when I searched a bit, I see that it is not recommended.
I have a JavaScript array containing some strings.
var quotes = new Array();
quotes[0] = "string 1";
quotes[1] = "string 2";
quotes[2] = "string 3";
quotes[3] = "string 4";
This code works well:
$(function() {
var random_quote = quotes[Math.floor(Math.random() * quotes.length)];
var $rand = $('div#randomQuote');
$rand.append(random_quote);
$rand.hide();
$rand.fadeIn("500");
});
However, I'm trying to run this every 15 seconds to renew the quote.
As I said, I have tried a while true loop and sleep function but it didn't work.
How can I achieve this?
Use setInterval
setInterval(yourFunction, timeInMilliseconds);
function randomQuote () {
var random_quote = quotes[Math.floor(Math.random() * quotes.length)];
var $rand = $('div#randomQuote');
$rand.append(random_quote);
$rand.hide();
$rand.fadeIn("500");
}
$(function () {
setInterval(randomQuote, 15000);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With