如何在循环内延迟两个函数?

我已经搜索了一整天,但我不知道如何解决它。

我想做的就是遍历一堆元素并对每个元素执行以下操作:

  • 添加班级

  • 等待 3 秒

  • 删除添加的类

  • 转到下一个元素

我已经尝试了很多东西,现在我有了这个:

/* Avatars is an array of elements */

var i = 0

function testimonialCarousel(avatars){

    const avatarsLen = avatars.length

    avatars[i].classList.add("focused-avatar");

    i++;


    if (i > 0){

        avatars[i-1].classList.remove("focused-avatar");

    };


    if (i < avatarsLen) {    

        setTimeout(testimonialCarousel.bind({}, avatars), 3000);

    } else{

        i = 0;

    };

};

我知道这里有很多问题已经涵盖了单个函数的延迟,例如:如何在 JavaScript 循环中添加延迟?


这不是我的情况。我可以实现它,以 3s 的间隔为每个元素添加类。我无法实现的是“删除课程”步骤。


有人可以帮助我吗?


慕姐8265434
浏览 153回答 1
1回答

拉丁的传说

好的,我已经找到了如何处理它:for (let i = 0; i <= avatarsLen; i++){&nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (i > 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; avatars[i-1].classList.remove("focused-avatar");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (i == avatarsLen) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return testimonialCarousel();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; avatars[i].classList.add("focused-avatar");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; balloonMessage.style.opacity = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; balloonName.style.opacity = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; balloonMessage.innerHTML = balloonContent[i].message;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; balloonName.innerHTML = "— " + balloonContent[i].name;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; balloonMessage.style.opacity = 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; balloonName.style.opacity = 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, 650)&nbsp; &nbsp; &nbsp; &nbsp; }, i*3000);&nbsp; /* <--- The solution lays here. */
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript