2012-02-18 11 views
2

私はjQueryを使用して自分のWebページにランダムな引用を表示しようとしています。しかし、while(true) { }のアプローチでは私の問題は解決されませんでしたが、少し検索したときには推奨されません。15秒ごとにJavaScriptコードを実行

私はいくつかの文字列を含むJavaScript配列を持っています。

var quotes = new Array(); 
quotes[0] = "string 1"; 
quotes[1] = "string 2"; 
quotes[2] = "string 3"; 
quotes[3] = "string 4"; 

このコードはうまく機能:

$(function() { 
    var random_quote = quotes[Math.floor(Math.random() * quotes.length)]; 
    var $rand = $('div#randomQuote'); 
    $rand.append(random_quote); 
    $rand.hide(); 
    $rand.fadeIn("500"); 
}); 

しかし、私は引用符を更新する15秒ごとにこれを実行しようとしています。

私が言ったように、私はしばらく真のループとスリープ機能を試しましたが、機能しませんでした。

どうすればこの問題を解決できますか?

答えて

7

使用setIntervalnew Array()コンストラクタを使用

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

は悪い習慣と見なされ、配列リテラルを定義する好ましい方法です。

+0

なぜあなたは 'setInterval'の引数として無名関数を使用していますか? – Quentin

+0

ベストプラクティスなので、 setIntervalはeval()のように機能するので、文字列の代わりに関数を使うことをお勧めします。 JavaScriptをよく読む;) – danwellman

+1

私は言い方をしましょう:既存の関数を直接渡すのではなく、引数なしで既存の関数を呼び出すだけの新しい関数を作成するのはなぜですか? – Quentin

関連する問題