[SOLVED] Javascript function when called twice does not execute

Issue

I am trying to understand a tutorial about function sequencing on ‘w3schools – Lesson: JS Async’, but i am stuck at the below example.

If you have a JS function that is called twice, apparently the order in which the function is called determines which function gets executed, in the example below i would expect the first function to be executed but it’s not

The essence of this lesson should be that the declaration of a function does not determine it’s execution order, only the way it’s called, but i can’t grasp it..

Can anyone elaborate or explain the logic of this syntax? Or what is happening under the hood in JS?

Link to tutorial: https://www.w3schools.com/js/js_callback.asp

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Function Sequence</h2>

<p>JavaScript functions are executed in the sequence they are called.</p>

<p id="demo"></p>

<script>
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

function myFirst() {
  myDisplayer("Hello");
}

function mySecond() {
  myDisplayer("Goodbye");
}

myFirst();
mySecond();
</script>

</body>
</html>

Solution

You can verify that both functions are called in the correct order by including a console.log statement in the myDisplayer function.

Because you’re overwriting the entire content of #demo each time you call the function, you’ll only get to see the result of the very last function call.

function myDisplayer(some) {
  console.log(some);
  document.getElementById("demo").innerHTML = some;
}

function myFirst() {
  myDisplayer("Hello");
}

function mySecond() {
  myDisplayer("Goodbye");
}

myFirst();
mySecond();
<p id="demo"></p>

Answered By – Đinh Carabus

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *