2013-02-12 32 views
-4

嗨我有这个代码可以让任何人知道如何在2秒内更改这个随机关键字。随机数组在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

你可能指的是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); 

UPDATE:

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代码:

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

意识到你是在调用'shuffleKeywords()'瞬间,而不是传递作为论据。 – 2013-02-12 11:41:39

+1

我的意思是你想'window.setTimeout(shuffleKeywords,2000)'而不是'window.setTimeout(shuffleKeywords(),2000)'。注意'()'。 – 2013-02-12 11:59:30

+0

对不起,刚开始工作。早晨喝咖啡之前,我的大脑缺乏功能,完全误解了它。 – leko 2013-02-12 12:00:45