简体   繁体   中英

How to add timer to bootstrap progress bar in javascript

I have a timer with the progress bar. the timer works fine. but I want to move the progress bar with the timer. I'm using the bootstrap progress bar. if I remove the bar variable from the function the timer works fine but with the progress, it stops working. any suggestions? thank you :)

 function startTimer(duration, display, bar) { var timer = duration, minutes, seconds; setInterval(function () { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; bar.css('width', minutes + '%'); if (--timer < 0) { timer = duration; } }, 1000); } window.onload = function () { var minutes = 60 * 15, display = document.querySelector('#time'); bar = document.querySelector('#progressBar'); startTimer(minutes, display, bar); };
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <div class="progress mx-auto mb-2" style="max-width: 300px;"> <div class="progress-bar bg-success" role="progressbar" id="progressBar" style="width: 100%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div> </div> <span id="time">15:00</span>

Use bar.style.width , .css() is a jQuery function.

For correct percentage, calculate total and remaining seconds and set bar width based on that

 function startTimer(duration, display, bar) { var timer = duration, minutes, seconds; setInterval(function () { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); var totalSeconds = 15 * 60 , remainingSeconds = minutes * 60 + seconds bar.style.width = (remainingSeconds*100/totalSeconds) + "%"; minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { timer = duration; } }, 1000); } window.onload = function () { var minutes = 60 * 15, display = document.querySelector('#time'); bar = document.querySelector('#progressBar'); startTimer(minutes, display, bar); };
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <div class="progress mx-auto mb-2" style="max-width: 300px;"> <div class="progress-bar bg-success" role="progressbar" id="progressBar" style="width: 100%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div> </div> <span id="time">15:00</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM