Azeem Haider Azeem Haider - 1 month ago 5
Javascript Question

Pass event object in a javascript function

Sometime you see that we need

event
object in javascript.

Here is some code which is not working fine for me.

function test(e){
console.log(e);
e.preventDefault();
}
setTimeout(test, 1000);


When I run it
e
is undefined.

How can I pass the
event
object ?

Answer

setTimeout() does not pass an event object to its callback. And, even if you do find some way to get access to an event object in setTimeout(), it will be too late at that point to call e.preventDefault() because the default action will have already occurred.

So, your current approach to solving whatever problem you're trying to solve will not work. If you back up a few steps and explain the actual problem you're trying to solve, we could probably help you find a different way to solve it.

FYI, this type of question is known as the XY Problem where you describe a problem with your solution rather than the actual real problem you're trying to solve. An XY question vastly limits how we can help you.