JSFiddle - React, Tailwind, and code Playground
by tchaffee
HTML
<div id="output"></div>
JavaScript
// Use jquery deferred pipe chaining to force async functions to run sequentially
var dfd = $.Deferred(),
dfdNext = dfd,
x,
values = [],
// Outputs values, you don't need to understand this to understand the example.
updateDom = function (el, val) {
$(el).append('<p>Value is: ' + val + '</p>');
},
// Simulates $.ajax, but with predictable behaviour.
// You only need to understand that higher 'value' param will finish earlier.
simulateAjax = function (value) {
var dfdAjax = $.Deferred();
setTimeout(
function () {
dfdAjax.resolve(value);
},
1000 - (value * 100)
);
return dfdAjax.promise();
},
// This would be a user function that makes an ajax request. In real code
// you would replace simulateAjax with $.ajax.
requestAjax = function (value) {
return simulateAjax(value);
};
// Starts things running. You should be able to put this anywhere in the script,
// including at the end and the code will work the same.
dfd.resolve();
// Deferred pipe chaining.
// What you want to note here is that an new ajax call will not start until the previous
// ajax call is completely finished.
for (x = 1; x <= 4; x++) {
values.push(x);
dfdNext = dfdNext.pipe(function () {
var value = values.shift();
return requestAjax(value).
done(function(response) {
updateDom('#output', response);
});
});
}