Progress bar interview with mike
by leethelobster
HTML
<div class="c">
<div class="bar">
</div>
</div>
<button>
load
</button>
CSS
.c {
background: #ccc;
height: 20px;
width: 400px;
}
.bar {
background: green;
width: 0;
height: 100%;
transition: width 0.1s linear;
}
JavaScript
/* // 1. Make a progress bar from 0-100 */
document.querySelector('button').addEventListener('click', () => {
onLoaderProgress();
});
let currentCount = 100;
let first = true;
let currentProgress = 0;
const startTime = new Date().getTime();
// Value from 0-100
const onLoaderUpdate = (newVal) => {
document.querySelector('.bar').style.width = newVal + '%';
document.querySelector('.bar').innerHTML = `${newVal}%`;
// timeout is at 200ms to let the 0.1s animation finish
if(newVal === 100) setTimeout(onLoaderComplete);
}
const onLoaderComplete = () => {
alert("Loader is completed in: "+((new Date().getTime() - startTime) / 1000)+" seconds");
}
// Method that responds to an update 'event'
const onLoaderProgress = () => {
currentProgress = Math.min(currentProgress + Math.random() * 9 + 1, 100);
onLoaderUpdate(currentProgress);
if(currentProgress < 100) {
setTimeout(onLoaderProgress, Math.round(Math.random() * 100)+0.1);
}
}