The word callback
means that a function will be called back by some code at some point in time. The word callback
doesn't specify or mean the way how callback function is defined.
Usually, a callback is a function passed as an argument to another function. The body of the callback function can reside in a global scope or within the other function or class method.
For example:
const callback = () => console.log('Hello, world');
setTimeout(callback, 1000);
In this case, the body of the callback is defined in the global space, and it is passed as an argument to setTimeout
.
Second option:
const startMyTimer = () => {
const callback = () => console.log('Hello, world');
setTimeout(callback, 1000);
};
In this case, the callback is defined in the body of another function, startMyTimer
, and passed as an argument to setTimeout
.
Third option:
const startMyTimer = () => {
setTimeout(() => console.log('Hello, world'), 1000);
};
Here the body of the callback is declared within the setTimeout
function call and passed into it as a parameter.
Array example:
const callbacks = [
() => console.log('hello'),
() => console.log('world'),
];
callbacks.forEach((cb) => cb());
This example demonstrates that callbacks do not necessarily need to be passed as a parameter but can also be stored in variables or arrays.
Saved callback scenario, based on @slebetman's comment:
class MyObject {
constructor() {
this.callback = null;
}
runIt() {
// do some work here
// ...
// and then call the callback
this.callback();
}
}
const obj = new MyObject();
obj.callback = () => console.log('Hello, world!');
obj.runIt();
This shows that a callback can be saved as a field of an object and then executed after some work is done.
Please let me know if this helps.