我正在撰寫一個普通的 javascript 函式來向我的網站添加頁面滾動影片。問題是我希望事件偵聽器暫停指定的毫秒時間,以便為影片完成提供時間,因為如果我正常滾動,影片將一個接一個地發生多次。
/* Event handler for scroll event */
// This is a function which allows a time to be passed in miliseconds. This function will then cause a sleep effect for the specified ms time
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Initial state
var iniState = 0;
// Adding scroll event
window.addEventListener('scroll', function(){
// Detects new state and compares it with the old one
if ((document.body.getBoundingClientRect()).top > iniState)
console.log('up');
else
console.log('down');
// Saves the new position for iteration.
iniState = (document.body.getBoundingClientRect()).top;
sleep(2000).then(() => { console.log("test"); });
});
我嘗試了超時功能,但這只會延遲事件偵聽器而不是暫停一段時間。如果這使問題更容易理解,這是瀏覽器中控制臺的鏈接。
總之,我試圖讓一個事件偵聽器來監聽滾動事件,然后等待 2000 毫秒以等待影片完成。在此之后,事件偵聽器將再次開始偵聽滾動事件。
uj5u.com熱心網友回復:
我相信每次當瀏覽器檢測到滾動事件時,它都會使用您的模板創建一個新函式并放入堆疊中。
例如:檢測到滾動:7:41:20s call stack = [ function_created_at_7:41:20s]
在 7:41:21s 檢測到下一個滾動:
call stack = [ function_created_at_7:41:20s,
function_created_at_7:41:21s
]
由于 promise 和 timeout 是異步執行的,它們會等待并留在呼叫堆疊中。
2000s 過去后,function_created_at_7:41:20s會執行sleep 的回呼
您可能必須使用全域參考和一些 if 來保持滾動功能進入睡眠狀態。
uj5u.com熱心網友回復:
let is_waiting = false;
document.addEventListener("scroll",(e) => {
if(!is_waiting) {
console.log("scrolling...");
is_waiting = true;
setTimeout(() => {
is_waiting = false;
},2000);
}
})
uj5u.com熱心網友回復:
let lastScrollStart
window.addEventListener('scroll', () => {
const scrollStart = lastScrollStart = performance.now() // timestamp
const elAnimated = document.querySelector(...)
elAnimated.addEventListener('animationend', function onAnimationEnd() {
elAnimated.removeEventListener('animationend', onAnimationEnd)
if (scrollStart === lastScrollStart) {
...
}
})
})
uj5u.com熱心網友回復:
只需添加事件偵聽器,呼叫后將其洗掉,然后設定超時以再次添加它。
function scrollHandler() {
window.removeEventListener('scroll', scrollHandler);
// Detects new state and compares it with the old one
if ((document.body.getBoundingClientRect()).top > iniState)
console.log('up');
else
console.log('down');
// Saves the new position for iteration.
iniState = (document.body.getBoundingClientRect()).top;
setTimeout(() => window.addEventListener('scroll', scrollHandler), 2000);
}
window.addEventListener('scroll', scrollHandler);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/392442.html
標籤:javascript
上一篇:為什么兩種寫法的輸出不一致?
