const parent = document.querySelector(".box .line-count"); const time = document.querySelector(".box .toolbar__item"); const colorLight = [ { color: "red", time: 4 }, { color: "yellow", time: 3 }, { color: "green", time: 6 }, { color: "yellow", time: 3 }, ];
let currentIndex = 0;
let currentTime = Date.now();
let allTime = colorLight.reduce((pre, cur) => pre + cur.time, 0);
function getCurrentLight(lightArr) { update(lightArr); return { color: currentLight(lightArr).color, remain: currentLight(lightArr).time - activeLight(currentTime), }; }
const currentLight = (arr) => arr[currentIndex];
const activeLight = () => (Date.now() - currentTime) / 1000;
const update = (arr) => { let disTime = activeLight(); disTime = disTime % allTime; currentTime += allTime * Math.floor(disTime / allTime) * 1000; while (true) { disTime -= currentLight(arr, currentIndex).time; if (disTime < 0) break; currentTime += currentLight(arr, currentIndex).time * 1000; currentIndex = (currentIndex + 1) % arr.length; } }; function __update() { const current = getCurrentLight(colorLight); parent.className = `line-count active-${current.color}`; time.textContent = Math.floor(current.remain); } __update(); setInterval(() => { __update(); }, 1000);
|