为mousemove事件添加延迟

时间:2019-10-28 21:24:24

标签: javascript events mousemove

我在mousemove事件上运行此功能。功能性是迭代一张img列表,然后每次都移到顶部(z索引)。这是正确的,但是mi问题是脚本运行得非常快,图像显示得非常快。如何为函数或事件添加延迟?我尝试使用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>

2 个答案:

答案 0 :(得分:1)

使用Debounce

类似的事情应该起作用(从changeBkg内部删除超时):

//change 300ms to suite your needs
<section class="main" onmousemove="debounce(changeBkg(event),300)"></section>
  

反跳是一个高阶函数,它是一个返回另一个函数的函数。这样做是为了围绕func,wait和即时函数参数以及timeout变量形成一个闭包,以便保留它们的值。

进一步阅读/如果您喜欢自己实现:Debounce Article

答案 1 :(得分:0)

已解决。 因为我需要的是某种动画,所以我用greensock弄清楚了 因此,我的事件在此动画中包含,当animPlay为true且播放时间为false时触发

        if(animPlay){
        animPlay = false
        var tl = new TimelineMax();
        tl.staggerFromTo(bkgImgs, .5, {zIndex:0}, {zIndex:1}, .15, 0)
        .set(bkgImgs, {zIndex:0, onComplete:() => animPlay = true}, '+=0' )

    }