Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 852
Muhammet Can Avatar asked Mar 29 '26 22:03

Muhammet Can


1 Answers

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);
});
like image 72
Quentin Avatar answered Apr 02 '26 02:04

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!