最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Running JavaScript code every 15 seconds - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 9

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

发布评论

评论列表(0)

  1. 暂无评论