JSFiddle - React, Tailwind, and code Playground
HTML
<h4>Processing Data... <span></span></h4>
<h5>(jsFiddle applies a 2 second response delay - after receiving each request)..</h5>
<hr/>
<div class="prod_SKU" data-value="abcd">--</div>
<div class="prod_SKU" data-value="wxyz">--</div>
<div class="prod_SKU" data-value="zyxw">--</div>
<div class="prod_SKU" data-value="dcba">--</div>
CSS
h4 {
color: red;
margin: 0;
}
h4 > span {
font-size: .75em;
color: black;
}
h4 > span:before {
content: 'Elapsed Time: ';
}
h5 {
color: #888;
font-style: italic;
font-weight: normal;
margin: 0;
}
.prod_SKU:before {
content: 'Weight: ';
}
JavaScript
/* to show the script is still asynchronous */
var timer = 0;
var ms = 0;
var ticker = $('h4 > span');
function getCurrentTime(i) {
return i > 100 ? i / 100 + ' sec' : i + ' ms';
}
function setTime() {
ms++;
ticker.text(getCurrentTime(ms));
}
timer = setInterval(setTime, 10);
/* end time ticker */
var def = $.Deferred();
var promise = def.promise();
$('.prod_SKU').each(function() {
var prod = $(this);
var sku = prod.attr('data-value');
promise = promise.then(function() {
prod.text('Request Sent at ' + getCurrentTime(ms));
return $.ajax('/echo/json/', {
method: 'post',
dataType: 'json',
data: {
json: '{"sku": "' + sku + '", "weight": "' + Math.random() * 100 + '", "sent": ' + ms + '}',
delay: 2
},
success: function(result) {
$('[data-value="' + result.sku + '"]').text(result.weight + ' | received at ' + getCurrentTime(ms) + ' sent at ' + getCurrentTime(result.sent));
}
});
});
});
promise.done(function() {
$('h4').css({
'color': 'green'
}).text('All Data Loaded!');
clearInterval(timer);
});
def.resolve();
console.log('Just to show we finished before the looper');