I have a button to go up to the top of the page when clicking on it. It works perfectly for me, when I click on it it goes up and at a smooth speed. But what I want is that when I hit the button, wait 2 seconds and it's already executed, and I don't know what I'm doing wrong that doesn't work.
this is my code
const returnTopButton = document.querySelector("#returnTop"); //disparador
const targetScroll = document.querySelector("#top"); //objetivo
setTimeout(
returnTopButton.addEventListener("click", () => {
targetScroll.scrollIntoView({ behavior: "smooth" });
}),
2000 //tiene que tardar 2 segundos desde que hago click para que se ejecute la función
);
It must be the other way around, in the event listener you must put all your logic, this is associated 1 time to the element and everything inside it will be executed. Try: