問題:點擊按鈕啟動定時器移動方塊,動畫未完成時再次點擊其他按鈕,舊定時器未清除導致多個定時器並行、方塊亂跳。
var timer = null;
function show(jc) {
if (parseInt(tt) < jc*300) {
timer = setInterval(() => right(jc), 30); // 覆蓋 timer,舊定時器失去引用無法清除
} else {
timer = setInterval(() => left(jc), 30);
}
}
function show(jc) {
clearInterval(timer); // 關鍵:清除舊定時器
if (parseInt(tt) < jc*300) {
timer = setInterval(() => right(jc), 30);
} else {
timer = setInterval(() => left(jc), 30);
}
}
class Slider {
constructor(el, step=30, duration=30) {
this.el = el; this.step = step; this.duration = duration;
this.timer = null; this.target = 0;
}
moveTo(pos) {
clearInterval(this.timer);
this.target = pos;
this.timer = setInterval(() => this.tick(), this.duration);
}
tick() {
const cur = parseInt(this.el.style.left) || 0;
if (Math.abs(cur - this.target) <= this.step) {
this.el.style.left = this.target + 'px';
clearInterval(this.timer);
} else {
this.el.style.left = (cur + (this.target > cur ? this.step : -this.step)) + 'px';
}
}
}
// 使用
const slider = new Slider(document.getElementById('B'));
document.querySelectorAll('.btn').forEach((btn, i) => {
btn.onclick = () => slider.moveTo(i * 300);
});
timer ID。clearInterval(timer)。requestAnimationFrame + CSS Transition 更流暢。