Callback
- A callback is a function passed as an argument to a function which runs asynchronously
- Callback function is called when the results are available
Timer functions using callback
setTimeout
setTimeout(pingMe, 3000);
function pingMe() {
console.log("get ready");
}
setInterval
setInterval(function(){
console.log(new Date())
}, 1000)
Loading script dynamically
- Loading script dynamically executes in asynchronous way.
- To execute some code once the script is loaded you can use callback approach.
function loadScript(url, callback) {
const script = document.createElement("script");
script.src = url
document.head.append(script);
script.onload = callback;
}
console.log("before loading script");
loadScript("https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js", function(){
console.log(moment().format());
});
//console.log(moment().format()); //error
console.log("after loading script");
Callback Hell/Pyramid of Doom
- If you want to load multiple script sequentially. you have to nest code.
- As calls become more nested, the code becomes deeper and increasingly more difficult to manage. This is called Callback Hell
loadScript("script1", function(){
loadScript("script2", function(){
loadScript("script3", function(){
});
});
});