javascript - 为 mousemove 事件添加延迟

标签 javascript events mousemove

我在 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/

相关文章:

c# - "Ghost"WinForms 中的 MouseMove 事件

javascript - Polymer 确定 dom-repeat items 上的最后一个 item

javascript - 可以用比正式接收的参数更多的参数调用 JS 函数吗?

node.js - 从标准输入读取时无法使用 CTRL D 触发 'end' 事件

c - 如何使用Wifi udp套接字编程控制鼠标指针

javascript - 按下键时响应鼠标移动

javascript - Ng-view on load 事件

javascript - 无法切换多个 div 的可见性,因为切换()分别跟踪每个元素

c# - 即使已设置,变量也会导致 NullReferenceException

javascript - 适用于桌面和移动设备的 jQuery 事件