Skip to main content

Command Palette

Search for a command to run...

Understand callback function in JS

Published
•2 min read•View as Markdown
Understand callback function in JS

What is a function callback?

Function callback is known as passing a function as an argument or you can say function as a perimeter

It is a way of handling tasks without blocking the main execution thread

Tasks that take time to execute for example reading a file, or sending a network request can be done with a callback method to run it on another thread without blocking the main thread

Need of function callback

We need a function callback for different things like

  • 1 Reading from a file

  • 2 Network request

and there are many more example

When a website reloads you will see your profile name or image immediately, does it make sense to load content (videos, post, and others) first and then load your profile name and image?

The loading of content will be considered here as a long-running task so we will load it later but we will load the profile name and image first.

Understanding with example

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

first()
second()
third()

// output will be 1 2 3

The output of this code will be 1 2 3

let us understand with another example

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

first()
setTimeout(second, 2000)
third()

// output will be 1 3 2

The output of this code will be 1 3 2

The above program is known as asynchronous programming in JS because it does not block the main thread of a program.

Here the code does not block the thread but it is running on another thread that's why it printed 1 3 2 whenever 2 seconds over the function second will be printed

But what if you want to print in the order 1 2 3 but 2 after 3-4 sec

let us understand with another example.

function first(){
  console.log(1)
}
function second(callback){
  setTIMEOUT(() => {
  console.log(2) // this will be e=executed after 3 seconds
  callback()
 }, 3000)
 }
function third(){
  console.log(3)
}

first()
second(third)

/* output wiil be 
1
2 // it will be printed after 3 second 
3
*/

So this is function callback in JS