0

This question is not about fixing a code,as I managed to do it, but to understand why it's happening.

The idea was to delay a pop-up window (with 2 buttons and 1 input text). Initially I used version-b(a setTimout function using an arrow function as a parameter) but buttons weren't responding to any interaction. After trying different things I tried extracting the arrow function, in version-b, into a regular function (version-a) and everything worked perfectly. I guess the issue is related to the way setTimeout() and arrow functions work but couldn't find the reason why it's happening.

VERSION-A:

let usrNameQs="";
function loadPopUp(){
    setTimeout(()=>{
      document.querySelector(".popup").style.display = "block";
      usrNameQs=document.querySelector("#userName");
      usrNameQs.value="";
      changeNamePlayer("");
  },500);
}
window.addEventListener("load",loadPopUp());

VERSION-B:

let usrNameQs="";
window.addEventListener("load",**setTimeout(()=>**{
  document.querySelector(".popup").style.display = "block";
  usrNameQs=document.querySelector("#userName");
  usrNameQs.value="";
  changeNamePlayer("");
},500)
);
EscFox
  • 23
  • 3
  • 1
    Version B doesn't work because of the syntax errors. Version A invokes the function immediately, using its return value (`undefined`) as the callback argument. – jsejcksn Jan 27 '23 at 11:18
  • 1
    Meaning the syntax is `window.addEventListener("load",loadPopUp);` without the brackets – mplungjan Jan 27 '23 at 11:21
  • 1
    "*TypeError: Failed to execute 'addEventListener' on 'EventTarget': parameter 2 is not of type 'Object'.*" should give it away why version B doesn't work. It still runs the timeout callback though. (And no, this has nothing to do with arrow functions) – Bergi Jan 27 '23 at 11:21
  • 2
    [^](https://stackoverflow.com/questions/75257313/logic-behind-settimeout-function-in-javascript/75257503#comment132798985_75257313) @mplungjan The [return value](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#return_value)’s type is `number`. – jsejcksn Jan 27 '23 at 11:54
  • 1
    If you want to add setTimeout to the load event you need more arrows since the returnValue of setTimeout is not a function but a number: `window.addEventListener("load",() => setTimeout(()=>{ },500))` – mplungjan Jan 27 '23 at 11:59

0 Answers0