JSFiddle - React, Tailwind, and code Playground
by eelyafi
HTML
<!-- Make the progress bar advance from 0-100% full over the course of 3 seconds -->
<!-- Create a button that adds multiple progress bars to the page -->
<button>Progress!</button>
<!-- Allow any number of progress bars, but only allow 3 progress bars to run at any one time -->
CSS
.progress{
border: 1px solid blue;
height: 20px;
width: 400px;
margin: 10px auto;
}
.bar {
content: "1%";
width: 1%;
background: blue;
display: block;
height: 100%;
}
JavaScript
var bar = document.getElementsByClassName('bar')[0];
var delay = 100;
var barsArr = [];
var barsRunning = [];
var button = document.getElementsByTagName('button')[0];
button.addEventListener('click', function (e) {
var progress = document.createElement('DIV');
progress.className = 'progress';
var bar = document.createElement('DIV');
bar.className = 'bar';
progress.appendChild(bar);
document.body.appendChild(progress);
if (barsRunning.length < 3) {
barsRunning.push(bar);
} else {
barsArr.push(bar);
return;
}
run(bar);
}, false);
function run (bar) {
var token = setInterval(function () {
console.log(bar, 'bar', bar.style.width);
var width = parseInt(bar.style.width, 10);
width = width || 0;
width += 3;
if (width > 100) {
width = 100;
clearInterval(token);
barsRunning.shift();
var newBar = barsArr.shift();
if (newBar) {
barsRunning.push(newBar);
run(newBar);
}
}
console.log(width);
bar.style.width = width + '%';
bar.innerHTML = width + '%';
}, 100);
}