执行后延迟 JavaScript

Give delay in JavaScript after execution

document.addEventListener("wheel",changeTopicBackground);

function changeTopicBackground(){
    if(document.getElementById("topicBackground").style.getPropertyValue("background-image")===`url("yy.jpg")`){
        document.getElementById("topicBackground").style.backgroundImage = "url('firstDevil.png')";
    }
    else{
        document.getElementById("topicBackground").style.backgroundImage = "url('yy.jpg')";
    }
}

我也尝试过 setTimeout() 和 setInterval(),但是如果我在函数内部使用 setTimeout,那么它会在那之后执行函数内部的块...并且 setInterval 会重复,这是不需要的.

问题是:如何在函数内的代码执行完后停止1sec的wheel事件监听?

您可以在函数触发时移除侦听器,并在一秒后使用 setTimeout 恢复它:

document.addEventListener("wheel", changeTopicBackground);

function changeTopicBackground() {
  console.log("wheeled!")
  document.removeEventListener("wheel", changeTopicBackground)
  setTimeout(() => document.addEventListener("wheel", changeTopicBackground), 1000)
}