我在 mousemove 事件上运行此函数。其功能是迭代图像列表并一次将每个图像移动到顶部(z 索引)。这是正确的,但我的问题是脚本运行得非常快并且图像显示得非常快。如何为函数或事件添加延迟?我尝试使用 setTimeOut 没有任何积极效果
这是代码
// creating variables
const imgQty = 6;
const holder = document.getElementById('holder')
var counter = 1;
var isMoving = false;
var bgtimeout, imgtimeout;
var bkgImgs = []
// this creates the containers for each img
for (let i = 1; i <= imgQty; i++) {
var newDiv = document.createElement('div');
newDiv.classList.add('background')
newDiv.classList.add(`background--${i}`)
newDiv.setAttribute("style", `background-image: url('imgs/${i}.jpg'); z-index: 0;`);
holder.appendChild(newDiv);
bkgImgs.push(newDiv)
}
//this moves the counter and also hides the images when the mouse is not moving
function changeBkg(e){
counter >= imgQty ? counter = 1 : counter++
holder.classList.add('isActive')
clearTimeout(bgtimeout);
clearTimeout(imgtimeout);
bgtimeout = setTimeout(function(){holder.classList.remove('isActive')}, 150);
moveImgs();
}
// and here is where my issue is, this function is working but not as I expected
function moveImgs(){
for(var i = 0; i < bkgImgs.length; i++){
if(bkgImgs[i].classList.contains(`background--${counter}`)){
bkgImgs[i].style.zIndex = "1";
} else{
bkgImgs[i].style.zIndex = "0";
}
}
}
我的逻辑对吗?或者我必须重新考虑代码吗?
事件在以下部分触发:
<section class="main" onmousemove="changeBkg(event)"></section>
最佳答案
使用Debounce
这样的事情应该可以工作(从changeBkg内部删除超时):
//change 300ms to suite your needs
<section class="main" onmousemove="debounce(changeBkg(event),300)"></section>
A debounce is a higher-order function, which is a function that returns another function. This is done to form a closure around the func , wait , and immediate function parameters and the timeout variable so that their values are preserved.
进一步阅读/如果您喜欢自己实现:Debounce Article
关于javascript - 为 mousemove 事件添加延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58598607/