Skip to content
Advertisement

how to turn this piece of code inside a loop

I have started to learn JavaScript, and I was trying to make an animation of a loading bar, but I do not know how to make it repeat the function after the bar reaches to the end, I thought maybe with a loop I can get the outcome I wanted, but I am still learning about loops, I have tried different methods, and changing the whole code, and nothing worked.

const progressBar1 = document.getElementsByClassName
('progress-bar1')[0]
setInterval(() => {
  const computedStyle = getComputedStyle(progressBar1)
  const width = parseFloat(computedStyle.getPropertyValue
    ('--width')) || 0
  progressBar1.style.setProperty('--width', width + .1)
},5)

Can anyone help me? Thank you for your time.

Advertisement

Answer

You already have a loop by using setInterval to call this set of code each 5ms.

One way you could have this continue to loop back the growth progress is by setting a max-width. I’m not sure if there is a parent container you could query for width or if you wanted to set a constant, but just check each time the width is greater than max, reset back to 0 and grow again.

const progressBar1 = document.getElementsByClassName
('progress-bar1')[0];
const widthMax = 300;

setInterval(() => {
  const computedStyle = getComputedStyle(progressBar1);
  const widthCurrent = parseFloat(computedStyle.getPropertyValue
    ('--width')) || 0;

  const width = widthCurrent > widthMax ? 0 : widthCurrent;
  progressBar1.style.setProperty('--width', width + .1);
}, 5);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement