Javascript 使用setTimeout函数时出现问题
我一直无法正确使用setTimeout函数,因此我尝试编写一个示例脚本来更新进度条,但同样,它不起作用。相反,整个程序在进度条更新为100%之前运行。有人能看看这个代码,告诉我我做错了什么吗 我试图使用的代码来自 谢谢Javascript 使用setTimeout函数时出现问题,javascript,jquery,settimeout,Javascript,Jquery,Settimeout,我一直无法正确使用setTimeout函数,因此我尝试编写一个示例脚本来更新进度条,但同样,它不起作用。相反,整个程序在进度条更新为100%之前运行。有人能看看这个代码,告诉我我做错了什么吗 我试图使用的代码来自 谢谢 <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://digitalbush.com/wp-content/uploads/2007/02/jqueryprogressbar.js" type="text/javascript"></script>
<title>Progress Bar test</title>
</head>
<body>
<style>
/* progress bar container */
#progressbar{
border:1px solid black;
width:200px;
height:20px;
position:relative;
color:black;
}
/* color bar */
#progressbar div.progress{
position:absolute;
width:0;
height:100%;
overflow:hidden;
background-color:#369;
}
/* text on bar */
#progressbar div.progress .text{
position:absolute;
text-align:center;
color:white;
}
/* text off bar */
#progressbar div.text{
position:absolute;
width:100%;
height:100%;
text-align:center;
}
</style>
<div id="progressbar"></div>
<input type='button' value='start' onClick='run()' />
<script>
function run() {
for (i=0; i<100; i++) {
setTimeout( function() {
$("#progressbar").reportprogress(i);
}, 500);
}
}
</script>
</body>
</html>
进度条测试
/*进度条容器*/
#进度条{
边框:1px纯黑;
宽度:200px;
高度:20px;
位置:相对位置;
颜色:黑色;
}
/*色条*/
#进度条进度分部{
位置:绝对位置;
宽度:0;
身高:100%;
溢出:隐藏;
背景色:#369;
}
/*条形图上的文本*/
#progressbar div.progress.text{
位置:绝对位置;
文本对齐:居中;
颜色:白色;
}
/*文本关闭栏*/
#progressbar div.text{
位置:绝对位置;
宽度:100%;
身高:100%;
文本对齐:居中;
}
函数运行(){
对于(i=0;i而言,问题在于变量i
成为闭包的一部分,并且在执行函数时,它已经等于100
您当前的代码创建了一百个引用同一变量(全局i)的超时。当所有函数执行时,i等于100,因此您将100作为当前进度报告100次
正确的版本应如下所示:
function run() {
var i = 0;
setTimeout( function updateProgress() {
$("#progressbar").reportprogress(i++);
if (i < 100){
setTimeout(updateProgress, 500);
}
}, 500);
}
函数运行(){
var i=0;
setTimeout(函数updateProgress(){
$(“#progressbar”).reportprogress(i++);
如果(i<100){
设置超时(updateProgress,500);
}
}, 500);
}
您可以查看javascript garden的部分解释和可能的其他解决方案。setTimeout
不是sleep
(javascript没有sleep
)
循环时,您将函数设置为在500毫秒内运行,然后立即将其设置为在500毫秒内再次运行,依此类推。因此,您有效地将其设置为在500毫秒内运行100次,并在第一次执行之前将i
设置为100(因为JS引擎在不到半秒的时间内运行循环100次)
你想要更像这样的东西:
var interval, i = 0;
interval = setInterval(function () {
if (i === 100) {
clearInterval(interval);
} else {
$("#progressbar").reportprogress(i);
i++;
}
}, 500);
现在还不清楚您期望的是哪种行为。您如何知道progressbar需要多长时间才能完成?换句话说,为什么超时首先是显示进度条的合适方式?在本例中,我试图让它在大约10秒内从0缓慢增加到100%。相反,它从0跳到0到100%之间没有任何中间环节。最终,我想在代码中实现这一点,涉及大量的处理和for循环,让用户知道它到底走了多远。是的,这就是我想要的。我想我现在对setTimeout的工作原理有了更好的理解。我只需要记住,脚本的其余部分将继续执行在setTimeout延迟触发之前取消。现在我来看看是否可以将其转移到更大的程序。谢谢!