JSFiddle - React, Tailwind, and code Playground

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 
2. Increment loader by random interval with random %
*/

document.querySelector('button').addEventListener('click', () => {
 onLoaderProgress();
});

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 = `${Math.floor(newVal)}%`;
  // timeout is at 200ms to let the 0.1s animation finish
  if (newVal === 100) {
  	requestAnimationFrame(onLoaderComplete);
  }
}

const onLoaderComplete = () => {
	alert("Loader is completed in: "+((new Date().getTime() - startTime) / 1000)+" seconds");
}


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);
  }
}

function incrementLoader() {
	let rand = Math.floor(Math.random() * 10) + 1;
  
  if (first) {
  	currentCount = 100 - rand;
    first = false;
  } else {
  	currentCount = currentCount - rand;
  }

	//document.querySelector('.bar').style.width = rand + '%';

  console.log('here');
  console.log(rand);
  console.log(currentCount);
  

  
  /* if (currentCount < 100) {
    incrementLoader();
  } */
  
  //
}