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 remended.
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?
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 remended.
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?
Share Improve this question edited Apr 19, 2014 at 15:31 Jason Aller 3,65228 gold badges41 silver badges39 bronze badges asked Feb 18, 2012 at 11:12 Muhammet CanMuhammet Can 1,3542 gold badges17 silver badges30 bronze badges2 Answers
Reset to default 9Use 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);
});
var quotes = ["string 1", "string 2", "string 3", "string 4"];
$(function() {
function doQuote() {
var random_quote = quotes[Math.floor(Math.random() * quotes.length)];
var $rand = $('div#randomQuote');
$rand.append(random_quote);
$rand.hide();
$rand.fadeIn("500");
}
setInterval(function() { doQuote() }, 150000);
});
Using the new Array()
constructor is considered bad practice and defining an array literal is the preferred method.