0

new to Javascript and it's quirks. Can somebody explain this to me? it works fine in CodeSandbox, but in VSCode and Chrome I'm hitting this problem:

setup() function not called in this code:

function init(){
  ...
}

function setup(){
  ...
}

init();
setup();

setup() function being called in this code:

function init(){
  ...
  setup();
}

function setup(){
  ...
}

init();

Why does it execute in the last example, but not in the first?

7
  • That should work either way as far as I can tell. Is this exactly how the code is structured in your actual project? Commented Feb 24, 2020 at 23:53
  • Could you show the entire code of init() ? Maybe you have some infinit loop in it and it never calls the next function... Commented Feb 24, 2020 at 23:54
  • whats iniside the init of the first example? Commented Feb 25, 2020 at 0:00
  • function init () { window.ctx.fillStyle = 'black'; window.ctx.fillRect(0,0,800,400); } Commented Feb 25, 2020 at 0:00
  • @llamaCaraDara edit your question rather than add code in the comments. How do you know that setup() is never called? Show this code as well. Commented Feb 25, 2020 at 0:01

1 Answer 1

1

Just remove this line document.addEventListener('DOMContentLoaded', init) and you're good to go.

DOMContentLoaded event is fired when your page is fully loaded and parsed. So, the following scenario was happening:

init();
setup();
init(); <--- due to DOMContentLoaded event
Sign up to request clarification or add additional context in comments.

1 Comment

Yup! that's what was happening. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.