im trying to change an html page with a delay of 3 sec when the user clicks on a specific div in the screen.
document.getElementById("specificDiv").addEventListener("click", setTimeout(document.getElementById("linkToAnotherPage").click(), 3000) )
however the eventListener doesnt work. when the page loads up it automatically clicks on the "linkToAnotherPage" after 3 sec have past since loading the page.
would love if someone could help me understand whats wrong here.
setTimeout
takes a function. If you don't pass a function, it will run the code immediately. If you pass a function though, the function will be invoked after the specified time. To demonstrate:
setTimeout(console.log('Hello World 2'), 5000)
setTimeout(() => console.log('Hello World 1'), 5000)
So your code should be updated to: document.getElementById("specificDiv").addEventListener("click", setTimeout(() => document.getElementById("linkToAnotherPage").click(), 3000));
if you want it to wait the 3s specified before executing the click.