There is a block inside the loader. For example, the time is 1 minute and 3 seconds = 63 seconds. The width of the loader can also be different, for example, 500 pixels. So how many pixels do you have to add every second to the width of the loader so that in 63 seconds it will fill up completely ??

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .content { padding-top: 40px; } .block { position: relative; width: 500px; margin: 0 auto; height: 5px; background: #dadada; overflow: hidden; } .block-inner { position: absolute; height: 100%; background: green; width: 0; transition: all .3s ease; } #play { display: block; margin: 10px auto; } .time-wrapper { text-align: center; width: auto; margin: 10px auto; } </style> </head> <body> <div class="content"> <div class="block" id="block"> <div id="loader" class="block-inner"></div> </div> <div class="time"> <div class="time-wrapper"> <span id="minutes"></span>m: <span id="seconds"></span>s </div> </div> <div class="button-set"> <button id="play">Play</button> </div> </div> <script> "use strict"; window.onload = function() { var minutes = 2, seconds = 0, block = document.getElementById('block'), loader = document.getElementById('loader'), blockWidth = block.offsetWidth, play = document.getElementById('play'), minutesBlock = document.getElementById('minutes'), secondsBlock = document.getElementById('seconds'), perSeconds = (minutes * 60) + seconds, percentage = (blockWidth / 100) / (perSeconds / 100); minutesBlock.innerHTML = minutes; secondsBlock.innerHTML = seconds; console.log('perSeconds = ' + perSeconds); console.log('persentage = ' + percentage); play.onclick = function() { var percent = 0; var isPlaying = setInterval(function() { if (minutes === 0 && seconds === 0) { clearInterval(isPlaying); } else { if (seconds === 0) { minutes--; minutesBlock.innerHTML = minutes; seconds = 60; } seconds--; percent += percentage; loader.style.width = percent + 'px'; secondsBlock.innerHTML = seconds; if (seconds === 0 && minutes !== 0) { seconds = 59; secondsBlock.innerHTML = seconds; minutes--; minutesBlock.innerHTML = minutes; } } }, 1000); } } </script> </body> </html> 

So I tried it, it seems to work, but sometimes a few pixels are missing. For one minute it fills the entire strip, and for 2 it remains a bit.

    1 answer 1

     var iter = 0; ... var isPlaying = setInterval(function() { ... loader.style.width = (++iter * blockWidth / perSeconds) + 'px'; 
    • does not work (((( - undefined Nov.
    • @undefined You copied my code incorrectly. - Igor
    • Yes, really, I am sorry, everything works, thanks. - undefined