JS 遍历+延时执行
JS 遍历+延时执行
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS 遍历+延时执行</title>
</head>
<body>
<div>
<ul id="ul">
</ul>
</div>
<script>
let myarr = [
{ title: 'a', score: 101 },
{ title: 'b', score: 120 },
{ title: 'c', score: 107 }
];
// 定义一个函数用于递归输出数组元素
function printWithDelay(arr, index = 0) {
// 检查是否已经遍历完所有元素
if (index < arr.length) {
// 输出当前元素
console.log(arr[index]);
let _ul = document.getElementById('ul');
_ul.innerHTML += '<li>'+arr[index].title+':'+arr[index].score+'</li>';
// 2秒后调用自身,处理下一个元素
setTimeout(() => {
printWithDelay(arr, index + 1);
}, 2000); // 2000毫秒 = 2秒
}
}
</script>
</body>
</html>