Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can you explain please what is a callback function?

Im a bit confused about this. What is a callback function in javascript?

Thanks!

2 Answers

Steven Parker
Steven Parker
243,318 Points

Often, a function starts a process that will take some time to finish, like a screen animation or a network transmission. Rather than make your program wait, it returns right away so your program can keep going.

But as one of its arguments it takes a callback function, which is a function that will be called at some point in the future when the other process has finished.

aha, Can you please give an easy example?

Thanks again!

Steven Parker
Steven Parker
243,318 Points

Sure here's one:

setTimeout(function(){ alert("later"); }, 3000);
alert("now");

The setTimeout function is passed a callback function and a time, in this example 3000ms or 3 seconds. Then, an alert is called separately.

If you run this, you will see the "now" alert right away, even though it it called after the setTimeout. Then, 3 seconds later, you will see the "later" alert when the callback function gets executed.

You are the man! great example. now its much clearer.