2 回答

TA貢獻1911條經驗 獲得超7個贊
要清除間隔,您必須保存的返回值 setInterval
const playAnimation = () => {
const pixels = window.pageYOffset
console.log("pixels:", pixels)
let interval // declare the variable
if (pixels >= 30) {
interval = setInterval(startCycle, 1000) // save the interval ID
} else {
clearInterval(interval) // clear the interval ID
}
}

TA貢獻1816條經驗 獲得超6個贊
您遇到的問題是您要不止一次設置間隔。每次scroll觸發(fā)事件時,都會啟動一個間隔。
因此,添加一個布爾值以確保一次setInterval()只調用一個布爾值應該可以解決您的問題。
編輯:同樣,正如Alex Wayne提到的那樣,您應該將間隔保存在變量中,以便以后清除它。
例如:
var interval;
var isIntervalSet = false;
const playAnimation = () => {
const pixels = window.pageYOffset
console.log("pixels:", pixels)
if (pixels >= 30 && !isIntervalSet) {
interval = setInterval(startCycle, 1000)
isIntervalSet = true;
} else {
clearInterval(interval);
isIntervalSet = false;
}
}
document.addEventListener("scroll", playAnimation)
添加回答
舉報