It's the first time I encounter such an issue with the addEventListener() method. When I try to use it with a setTimeout, the function is automatically called, even though the addEventListener has a "click" property.
<button id="test">Test</button>
document.getElementById("test").addEventListener("click", setTimeout(myFunc, 2000));
function myFunc() {
console.log("Hello");
}
It's the first time I encounter such an issue with the addEventListener() method. When I try to use it with a setTimeout, the function is automatically called, even though the addEventListener has a "click" property.
<button id="test">Test</button>
document.getElementById("test").addEventListener("click", setTimeout(myFunc, 2000));
function myFunc() {
console.log("Hello");
}
Share
Improve this question
asked Dec 8, 2017 at 1:36
user8589236user8589236
2
-
2
because you call setTimeout and assign what it returns to the click handler. So since the timeout returns an id, you basically are doing
...Listener("click", 133)
– epascarello Commented Dec 8, 2017 at 1:38 - the second argument to addEventListener needs to be a function, not, as you have, the result of calling a function – Jaromanda X Commented Dec 8, 2017 at 1:39
3 Answers
Reset to default 5This would be what you want.
document.getElementById("test").addEventListener("click", function(){setTimeout(myFunc, 2000)});
function myFunc() {
console.log("Hello");
}
<button id="test">Test</button>
You can use setTimeout
inside the function that you call.
Jsfiddle
document.getElementById("test").addEventListener("click", myFunc);
function myFunc() {
setTimeout(function(){
console.log("Hello");
}, 6000);
}
You could keep the exact same code you have now but curry
your function via bind
vs. trying to invoke it while also trying to pass it as an argument.
document.getElementById("test").addEventListener("click", setTimeout.bind(null, myFunc, 2000));
function myFunc() {
console.log("Hello");
}
<button id="test">Click</button>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744265772a4565856.html
评论列表(0条)