要求:按给定数组,实现循环跑马灯
let arr = [
{ color: "red", time: 2000 },
{ color: "blue", time: 1000 },
{ color: "pink", time: 3000 },
{ color: "green", time: 4000 },
];
思路:使用闭包
let arr = [
{ color: "red", time: 2000 },
{ color: "blue", time: 1000 },
{ color: "pink", time: 3000 },
{ color: "green", time: 4000 },
];
let div = document.querySelector(".light");
let time1 = null;
function fn(b) {
if (b > arr.length-1) {
b = 0;
}
clearTimeout(time1);
time1 = setTimeout(() => {
div.style.backgroundColor = arr[b].color;
return fn(b + 1);
}, arr[b].time);
}
fn(0);
效果图:
![](https://i-blog.csdnimg.cn/blog_migrate/cc2f04dc588a7c954b7ff3777ecace43.gif)