2 回答
TA贡献1827条经验 获得超8个赞
这是一种方法,如何在单击按钮后每 5 秒对数组进行一次洗牌,如果多次单击它,它将始终取消先前的超时实例
var data = [{
"city": "seattle",
"state": "WA",
"population": 652405,
"land_area": 83.9
},
{
"city": "new york",
"state": "NY",
"population": 8405837,
"land_area": 302.6
},
{
"city": "boston",
"state": "MA",
"population": 645966,
"land_area": 48.3
},
{
"city": "kansas city",
"state": "MO",
"population": 467007,
"land_area": 315
}
]
const arrRandomIndex = []
const newArr = [];
while (arrRandomIndex.length !== data.length) {
const randomNum = Math.floor(Math.random() * data.length);
if (!arrRandomIndex.includes(randomNum)) {
arrRandomIndex.push(randomNum);
}
}
for (let i = 0; i < data.length; i++) {
newArr[i] = data[arrRandomIndex[i]];
}
let timeId;
document.getElementById('alter').addEventListener('click', function() {
clearTimeout(timeId);
timeId = setTimeout(_ => console.log('Random array', newArr), 5000)
})
<button id="alter">
AlTER
</button>
TA贡献2080条经验 获得超4个赞
给定的rows是一个节点列表tr
function randomise() {
for (const row of rows) {
const table = row.parentElement;
table.insertBefore(
row,
table.children[Math.floor(Math.random() * table.children.length)]
);
}
}
alter.addEventListener("click", () => {
randomise();
setInterval(function () {
randomise();
}, 5000);
});
- 2 回答
- 0 关注
- 119 浏览
添加回答
举报