0

Let's suppose we have

function first(){
  console.log(1);
}
function second(){
  console.log(2);
}
first();
second();

That will print

1
2

Now we put a timer inside the first() function.

function first(){
  // Simulate a code delay
  setTimeout( function(){
    console.log(1);
  }, 500 );
}
function second(){
  console.log(2);
}
first();
second();

Now this will give the opposite.

2
1

That's because Javascript is an event-driven language. My question is how to define a callback function in the above example, so as to wait and print

1
2

Thanks, Theo.

Theo
  • 3,099
  • 12
  • 53
  • 94

1 Answers1

0

You just call second() inside first().

function first() {
  // Simulate a code delay
  setTimeout(function() {
    console.log(1);
    second();
  }, 500);
}

function second() {
  console.log(2);
}

first();
holydragon
  • 6,158
  • 6
  • 39
  • 62