random array change in 2 second [closed]

2019-03-07 18:06发布

问题:

Hi I have this code can any one know how to change this random keyword in 2 seconds.

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:

You might be referring to window.setInterval(function,delay)

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

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

You could also use window.setTimeout(function,delay). setTimeout will launch after 2 seconds once.

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

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

UPDATE:

JS code:

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>