Understanding Asynchronous & Callback Functions in JavaScript🛳


When learning JavaScript, concepts like asynchronous, callbacks and anonymous functions can be hard to understand or distinguish. In this post, we will explore these concepts. To do this, I will use a popular JavaScript library called P5.js.
P5.js is a user-friendly tool for learning to code and create art. It is a free and open-source JavaScript library developed by a supportive community. P5.js welcomes artists, designers, beginners, educators, and anyone else! It even has an online web editor to try!
In this post, we explore the following:
📌 Normal (synchronous) functions
📌 Asynchronous functions
📌 Callback & Anonymous function
📌 Using these with p5.js
📌Normal JavaScript Function :
➡ Executes line by line (synchronously)
➡ Blocks execution until it finishes.
Example:
// Example 1: Normal JavaScript Function
function greet() {
console.log('hello!');
}
greet();
console.log('how are you?');
📌Asynchronous JavaScript Function :
➡ Allows JavaScript to continue running while waiting.
➡ Uses callbacks, promises, or async/await 🎭(will not discuss this)
Example using setTimeout:
// Example 2: Asynchronous JavaScript with setTimeout() Function
// Here, we use the built-in JavaScript function setTimeout function to mimic the delay
function greetAsync() {
setTimeout(function () {
console.log('hello!');
}, 2000);
}
greetAsync();
console.log('how are you?');
📌Asynchronous Functions in p5.js :
p5.js allow async functions, such as loading images dynamically.
➡ loadImage() is asynchronous.
➡ uses success and error callbacks.
Example:
// Function signature
loadImage('image.png', onSuccess, onError);
📌Handling Image Load in p5.js (Named Callback Function) :
p5.js allows handling errors using callback functions.
➡ A callback function is a function that is passed as an argument to another function.
➡ It is executed later, often after an asynchronous operation completes.
➡ Callbacks are commonly used in:
• Asynchronous programming (e.g. fetching data from an API)
• Event handling (e.g. button clicks, user inputs)
• Handling file reads in Node.js
In the following example, the callback functions we will use are 'Named' functions, meaning each of these callback functions has a name and its own function definition/body.
Example:
// Example 3: Handling Image Load in p5.js using 'Named' Callback Function)
// Here, we are trying to fetch an image from a URL, which may load successfully or may cause an error
function setup() {
createCanvas(400, 200);
loadImage('https://p5js.org/assets/img/p5js.svg', imageLoaded, imageError);
}
function imageLoaded(img) {
image(img, 50, 50, 300, 100);
}
function imageError() {
console.log('error: image could not be loaded!');
}
📌Handling Image Load in p5.js (Anonymous Callback Function) :
➡ An anonymous function is a function without a name.
➡ It is usually used when a function is not needed more than once.
➡ Anonymous are commonly used in:
• Callbacks
• Event listeners
• Short operations within array methods like map(), filter(), and forEach()
In this example, we use 'Anonymous' callback functions, which means these functions have no name and do not have their own function definition/body.
Example:
// Example 4: Using an Anonymous (function with no name) Callback Function for Image Handling
function setup() {
loadImage('invalid.jpg', function (img) {
createCanvas(400, 200);
image(img, 50, 50, 300, 100);
}, function () {
console.log('error: image could not be loaded!');
});
}
With a little bit of extra housekeeping code, the following are the output on Canvas:
Example: when image loaded successfully :
Example: when an image failed to load due to a given wrong file extension :
You can try it in the p5.js online editor here.
📌Difference Between Callback and Anonymous Functions :
➡ A callback function is passed to another function and executed later.
➡ An anonymous function is just a function without a name.
➡ A callback can be a named function or an anonymous function.
❖ EXAMPLE OF A NAMED CALLBACK:
function fetchData(callback) { callback('data received'); }
❖ EXAMPLE OF AN ANONYMOUS FUNCTION AS A CALLBACK:
function fetchData(function(data) { console.log(data); });
📌Pros and Cons of Callback Functions :
✅ PROS:
➡ Allows asynchronous operations without blocking execution.
➡ Useful for handling events, data fetching, and i/o operations.
➡ Can be reused and modularised if named.
❌ CONS:
➡ Can lead to 'callback hell' (nested callbacks making code harder to read).
➡ Harder to debug compared to promises and async/await.
📌Use Cases of Callback & Anonymous Functions :
✅ Callback Function Use Cases:
➡ Handling asynchronous operations (API calls, file reads, database queries).
➡ Event listeners (e.g. Button clicks, user interactions).
➡ Animations and time-based actions (setTimeout, setInterval).
✅ Anonymous Function Use Cases:
➡ Short, one-time-use functions (e.g. map(), filter(), reduce()).
➡ Passing a function directly into an event handler or callback.
➡ Preventing function name conflicts in certain scopes.
Summary :
Normal functions run synchronously, meaning they execute in order and block further execution until the current function finishes. This works well for simple tasks but is inefficient for time-consuming operations like fetching data or loading files.
Asynchronous functions allow the program to keep running while waiting for an operation to finish, which is crucial for tasks like loading images, making API requests, or reading files. Without this, the program would freeze while waiting. In P5.js, functions like loadImage()
load images asynchronously to avoid delays in rendering.
Anonymous functions are helpful for short tasks where naming a function isn't needed. They are often used in callbacks and passed as arguments for later execution. Callback functions are essential for managing asynchronous operations and events, ensuring actions happen when needed.
While anonymous functions and callbacks can be used together, overusing anonymous functions can make code hard to read and debug. To simplify asynchronous programming and avoid "callback hell", deeply nested callbacks, modern JavaScript offers Promises and async/await
, which provide a cleaner, more readable way to handle asynchronous tasks.
Subscribe to my newsletter
Read articles from Subrata Ch directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Subrata Ch
Subrata Ch
Software Engineer & Consultant