Search code examples
javascriptaddeventlistenertimedelay

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')";
    }
}

I've tried setTimeout() and setInterval() also, but if I use setTimeout inside the function then it'll execute the block inside the function after that time... and setInterval will repeat which is not desired.

Question is: How can I stop taking wheel event listener for 1sec after the code inside the function is executed?


Solution

  • You can remove the listener when the function fires and use setTimeout to restore it after one second:

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