In the below code snippet, on click of a button, progress bars are added one by one. The bar shows up for 3 seconds. If you continuously click on the button, it will keep adding progress bars. The next bar will start after the previous bar finishes animating.
Is there anyway to make the code better?
;(function(window, document, undefined) {
'use strict';
var container = document.getElementsByClassName('container')[0];
var button = document.getElementsByTagName('button')[0];
var progressBar = document.getElementsByClassName("bar-container")[0];
var promise = Promise.resolve();
button.addEventListener('click', function() {
var newProgressBar = progressBar.cloneNode(true);
container.appendChild(newProgressBar);
promise = promise.then(function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
newProgressBar.classList.add('active');
setTimeout(function() {
resolve();
}, 3000);
}, 0);
});
})
});
})(window, document);
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.bar-container{
width: 100%;
background: #ccc;
border: 1px solid #eee;
margin-bottom: 10px;
}
.loader{
height: 20px;
background: #434334;
width: 0px;
transition: width 3s ease;
}
.active .loader{
width: 100%;
}
</style>
</head>
<body>
<div class="container"></div>
<div style="display: none">
<div class="bar-container">
<div class="loader">
</div>
</div>
</div>
<button id="button">click me</button>
<script src="script.js"></script>
</body>
</html>
emphasized text
setTimeout(resolve, 3000);\$\endgroup\$