看了另外一张帖子,关于倒计时组件的,就自己写了一个,大家帮忙看下,写得怎么样?有什么问题,可以指出来!
<div class="time"></div>
function countdown(time) {
let lastTime = Date.now();
let rafId;
function refresh() {
const curTime = Date.now();
const more = curTime - lastTime - 1000;
if (more > 0) {
lastTime = curTime + more;
const nextTime = time--;
if (nextTime === 0) {
cancelAnimationFrame(rafId);
return;
}
update(time);
}
rafId = requestAnimationFrame(refresh);
}
function update(restTime) {
const h = restTime > 3600 ? Math.floor(restTime / 60) : 0;
const m = Math.floor((restTime - h * 3600) / 60);
const s = restTime - h * 3600 - m * 60;
const dom = document.querySelector('.time');
dom.innerHTML = `剩余${h}小时${m}分钟${s}秒`;
}
refresh();
update(time);
}
countdown(1000);