<h1>Demostrate callbacks</h1>
<p>
Callback is a way to delegate the execution of an “outter” function to a caller function :)
</p>
<p>
Execution chaining is a bit of a hassle and usually done in a sequesce, not in parallel.
</p>
<h2>Three examples</h2>
<ul>
<li>Call getUser function</li>
<li>Call getLanguages function</li>
<li>Call both functions and act only uppon success of both</li>
</ul>
JavaScript
// functions that perform ajax requests
var getUser = function(callback){
$.ajax({
type: 'GET',
url: '/echo/json',
data: { json: { /*---*/ }, delay: 3 },
success: function(){ callback('getUser success'); },
error: function() { throw new Error('getUser error') }
});
};
var getLanguages = function(callback){
$.ajax({
type: 'GET',
url: '/echo/json',
data: { json: { /*---*/ }, delay: 5 },
success: function(){ callback('getLanguages success'); },
error: function() { throw new Error('getLanguages error'); }
});
};
// call getUser function
var t1 = new Date()*1;
getUser(
function(resp){
var deltat = new Date() * 1 - t1;
console.log(resp + ' in ' + deltat + 'ms');
}
);
// call getLanguages function
var t2 = new Date()*1;
getLanguages(
function(resp){
var deltat = new Date() * 1 - t2;
console.log(resp + ' in ' + deltat + 'ms');
}
);
// call both functions and only act uppon success of both
var t3 = new Date()*1;
getUser(function(resp1){
getLanguages(function(resp2){
var deltat = new Date() * 1 - t3;
var resp = [resp1, resp2, 'in ' + deltat + 'ms'];
console.log(resp);
})
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.