javascript - addEventListener + setTimeout - Stack Overflow

It's the first time I encounter such an issue with the addEventListener() method.When I try to us

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
Add a ment  | 

3 Answers 3

Reset to default 5

This 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

相关推荐

  • javascript - addEventListener + setTimeout - Stack Overflow

    It's the first time I encounter such an issue with the addEventListener() method.When I try to us

    7天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信