Muhammet Can
Muhammet Can

Reputation: 1354

Running JavaScript code every 15 seconds

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?

Upvotes: 2

Views: 7146

Answers (2)

danwellman
danwellman

Reputation: 9273

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.

Upvotes: 1

Quentin
Quentin

Reputation: 944441

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);
});

Upvotes: 9

Related Questions