简体   繁体   English

addEventListener + setTimeout

[英]addEventListener + setTimeout

It's the first time I encounter such an issue with the addEventListener() method. 这是我第一次使用addEventListener()方法遇到这样的问题。 When I try to use it with a setTimeout, the function is automatically called, even though the addEventListener has a "click" property. 当我尝试将其与setTimeout一起使用时,即使addEventListener具有“ click”属性,也会自动调用该函数。

<button id="test">Test</button>

document.getElementById("test").addEventListener("click", setTimeout(myFunc, 2000));

function myFunc() {
  console.log("Hello");
}

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. 您可以在调用的函数内使用setTimeout 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. 你可以让你现在有完全相同的代码,但curry通过你的函数bind与尝试调用它,同时也试图把它作为参数传递。

 document.getElementById("test").addEventListener("click", setTimeout.bind(null, myFunc, 2000)); function myFunc() { console.log("Hello"); } 
 <button id="test">Click</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM