I have created a simple progress bar in HTML using JavaScript. The animation of this progress bar works correctly when the page is refreshed, but I want it to restart from the beginning once it completes and repeat indefinitely in a loop. However, the repetition and restart are not working properly and are not executing.
const progressBar = document.getElementById('progressBar');
function startProgressBarAnimation() {
progressBar.classList.remove('active');
setTimeout(() => {
progressBar.classList.add('active');
}, 100);
}
startProgressBarAnimation();
progressBar.addEventListener('transitionend', () => {
progressBar.style.transition = 'none';
progressBar.style.transform = 'translateX(100%)';
setTimeout(() => {
progressBar.style.transition = 'transform 5s linear';
startProgressBarAnimation();
}, 10);
});
.progress-bar-container {
width: 100%;
height: 3px;
background-color: #e0e0e0;
border-radius: 2px;
overflow: hidden;
}
.progress-bar {
width: 100%;
height: 100%;
background: linear-gradient(to right, #ff0008, #fad0c4, #ffecd2);
transform: translateX(100%);
transition: transform 5s linear;
}
.progress-bar.active {
transform: translateX(0);
}
<div class="progress-bar-container">
<div class="progress-bar" id="progressBar"></div>
</div>
3
Answers
If you want to apply an infinite animation to an element, use CSS not JS. This is because JS should not be involved in UI concerns, where possible, and CSS is hardware accelerated so will perform orders of magnitude better than JS. It also gives you finer control over easing and other properties
To use CSS you can use
animate
to define a keyframe animation which you then loop infinitely:You can combine
setTimeout
andsetInterval
. In each 1100 seconds you need to clean the board and schedule the progress to start anew:Here is the modified version of JavaScript.
There are many different methods to create a progress bar, but this approach is based on your original design.