更新时间:2023-01-11 21:31:56
问题在于变量i
成为闭包的一部分,并且在执行函数时已经等于100
.
The issue is that variable i
becomes the part of the closure and, when the function is executed, is already equal to 100
.
您当前使用的代码实际上会创建一百个引用同一变量(全局i)的超时.到执行所有功能时,i等于100,因此您将100作为当前进度报告为100.
The code you have currently literally creates a hundred of timeouts referencing the same variable(global i). By the time all of the functions are executed, i equals 100, therefore you report 100 as current progress 100 times.
正确的版本应如下所示:
The proper version should look like that:
function run() {
var i = 0;
setTimeout( function updateProgress() {
$("#progressbar").reportprogress(i++);
if (i < 100){
setTimeout(updateProgress, 500);
}
}, 500);
}
您可以检查javascript花园的闭包部分,以获取解释和可能的其他信息解决方案.
You could check closures part of javascript garden for explanation and possible other solutions.