JavaScript 进度条无限加载的问题

Problems with JavaScript progress bar loading infinitely

我在页面加载时和每个 eventListener 调用这个进度条函数,以便在用户与各种输入交互时向他们提供反馈。

问题:当我控制日志 (progressBar.style.width)

时,tt 似乎函数是 运行 "forever"

这是我的代码:

HTML

   <div class="progress">
       <div class="progress-bar" id="progressbar" role="progressbar" style="width: 0%" aria- 
       valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
   </div>

CSS + bootstrap

.bar_container{
    width: 50%;
    margin: 0px auto;
    margin-top: 20px;
}

加载栏的函数

progressBar = document.getElementById("progressbar")

   function loadBar() {
    let fill = 0
    window.setInterval(function() {

        fill += 60

        if (fill === 100) {
            clearInterval()
        } else {
            progressBar.style.width = fill + "%"
            console.log(progressBar.style.width) // seems like this function runs infinitely ???
        }

    }, 50)
}

使用事件侦听器调用函数

document.querySelector('#show-pm').addEventListener('change', function (e) {
    filters.hideAm = e.target.checked
    filterMeetings(filters)
    progressBar.style.width = "0%" //Intending to reset the progress to 0% ???
    loadBar()
})

感谢您的帮助!

你的问题是你填充了 60 所以填充永远不会是 100 所以永远不会间隔完成

如果你填满 1 则将其更改为

 function loadBar() {
    let fill = 0
    window.setInterval(function() {

        fill ++

        if (fill === 100) {
            clearInterval()
        } else {
            progressBar.style.width = fill + "%"
            console.log(progressBar.style.width) // seems like this function runs infinitely ???
        }

    }, 50)
}

如果它会上升到 60 那么你需要说

function loadBar() {
    let fill = 0
    window.setInterval(function() {

        fill +=60

        if (fill >= 100) {
            clearInterval()
        } else {
            progressBar.style.width = fill + "%"
            console.log(progressBar.style.width) // seems like this function runs infinitely ???
        }

    }, 50)
}