---
# System prepended metadata

title: Callback functions trick

---

# Callback functions trick

Why do we use callback functions?

In javascript, the compiler is compile the code line by line. But, it's not waiting the first line to finish to compile the second.

What if we have 2 functions and we want the first one be done before the second?

### Natural situation (No problem):

```javascript=
function first(){
  console.log("FIRST");
}

function second(){
  console.log("SECOND");
}

first();
second();
/*
 * output:
 * FIRST
 * SECOND
*/
```


### What if the first function take a lot of time (second will finish early):

```javascript=
function first(){
  setTimeout(function(){
    console.log("FIRST");
  }, 2000);
}

function second(){
  console.log("SECOND");
}

first();
second();

/*
 * output:
 * SECOND
 * FIRST
*/

```

### SOLUTION by using callback function
```javascript=
function first(cb){
  setTimeout(function(){
    console.log("FIRST");
    cb();
  }, 2000);
}

function second(){
  console.log("SECOND");
}


first(second);

/*
 * output:
 * FIRST
 * SECOND
*/

```