Async JavaScript
Topics
Callbacks
Topic Overview
Imagine ordering pizza. You don't stand at the door waiting - you give them your phone number (a callback) and they call you when it arrives. That's exactly how callbacks work in JavaScript!
What are callbacks? A callback is a function that runs AFTER something else finishes. It's like saying "when you're done with that, do this next."
Simple example with setTimeout:
setTimeout(function() {
console.log("This runs after 3 seconds");}, 3000);
Why we need callbacks:
- •Some operations take time (loading data, timers)
- •We don't want to freeze the page while waiting
- •Callbacks let other code run while waiting
Callback pattern:
function doSomethingAsync(callback) { // Simulate async operation setTimeout(() => { const result = "Operation complete!"; callback(result); }, 1000);}// Using it:
doSomethingAsync(function(result) {
console.log(result); // "Operation complete!"});
The "Callback Hell" problem:
// When you need multiple async operations:
getData(function(a) { getMoreData(a, function(b) { getMoreData(b, function(c) { // This nesting gets messy! }); }); });
Callbacks are the foundation of asynchronous JavaScript, but modern code uses Promises and async/await for cleaner syntax!
Ready to practice? Try the exercise below to reinforce your learning!
Try it yourself
Create a function that uses setTimeout with a callback to display a message after 2 seconds.