随机数组在2秒内变化

时间:2013-02-12 11:38:08

标签: javascript random

嗨,我有这个代码,任何人都知道如何在2秒内更改这个随机关键字。

function shuffle(a, b) {
    return Math.random() > 0.5 ? -1 : 1;

}

var keywords = ["<div>1</div>", "<div>2</div>", "<div>3</div>", "<div>4</div>", "<div>5</div>", "<div>6</div>", "<div>7</div>", "<div>8</div>", "<div>9</div>", "<div>10</div>", "<div>11</div>", "<div>22</div>", "<div>44</div>", "<div>32</div>", "<div>46</div>"];
var randomKeywords = keywords.sort(shuffle);


function luckcricket() {
    document.write(randomKeywords);
    alert('laad');
}


luckcricket();

1 个答案:

答案 0 :(得分:1)

您可能指的是window.setInterval(function,delay)

function shuffleKeywords() {
    randomKeywords = randomKeywords.sort(shuffle);
}

window.setInterval(function(){shuffleKeywords()},2000);

您也可以使用window.setTimeout(function,delay)。 setTimeout将在2秒后启动一次。

function shuffleKeywords() {
    randomKeywords = randomKeywords.sort(shuffle);
}

window.setTimeout(function(){shuffleKeywords()},2000);

<强>更新

JS代码:

function shuffle(a,b) {
    Math.random() > 0.5 ? -1 : 1;
}

var keyWord = ["<div>1</div>","<div>2</div>","<div>3</div>","<div>4</div>"];

window.setInterval(function() {
   keyWord = keyWord.sort(shuffle);
   // First line below will append divs to the document, Second line will replace it, use on of them
   document.getElementById('appended').appendChild(document.createTextNode(keyWord));
   document.getElementById('appended').innerHTML = keyWord;
}, 2000);

HTML code:

<html>
<body>
    <div id="appended"></div>
</body>
</html>