2012-12-18 111 views
1

我想用jquery ui progressbar。以下是我的代码jquery ui进度条不停止点击停止按钮

<!DOCTYPE html> 
<html> 
<head> 
<link href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet"> 
<script src="http://code.jquery.com/jquery-1.8.3.js"></script> 
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> 
<script> 
$(document).ready(function(){ 
$('#progressBar').progressbar({ 
      value: 1 
     }); 
}); 
var statusTracker ; 
var percentage = 0; 
function checkStatus() {//function to fill progress bar 
percentage = percentage +5; 
$("#progressBar > .ui-progressbar-value").animate({ 
    width : percentage + "%" 
}); 
statusTracker = setTimeout(function() {//call this function every 20ms 
    checkStatus() 
}, 20); 
} 

function startProgress(){ 
checkStatus(); 
} 

function stop(){//stop progress bar 


clearTimeout(statusTracker); 

} 
</script> 
</head> 

<body> 
<div id="progressBar" style="opcity:1; height:30px;width:500px;" ></div> 
<p> 
<input type="submit" value="Start" onclick="startProgress()"/> 

<input type="submit" value="Stop" onclick="stop()"/> 
</p> 
</body> 
</html> 

当我点击停止按钮进度条不停止。 我的clearTimeout()函数不起作用。 任何帮助将是可观的。

+0

@Cory我想通过点击stop()函数来停止这个进度条。 – ved

+0

以下是我上面的问题演示的链接 http://jsfiddle.net/kumarohit21/A7Yhs/ 点击停止按钮,必须停止进度条。 – ved

回答

2

您的超时时间太短。 setTimeout()的第二个参数是毫秒的数量,直到执行。在收到你的“停止”指令之前,浏览器已经将动画的所有(100/5)20个步骤放在堆栈上了。

尝试将超时间隔设置为500(1/2秒),然后重试。另外,我认为在这种情况下你最好用setInterval(),而不是使用无限的setTimeout()循环。事情是这样的:

var statusTracker; 
var percentage = 0; 

function checkStatus() { 
    percentage = percentage + 5; 
    $("#progressBar > .ui-progressbar-value").animate({ 
     width : percentage + "%" 
    }); 
    if (percentage == 100) stop(); 
} 

function startProgress() { 
    statusTracker = setInterval(checkStatus, 500); 
} 

function stop() { 
    clearInterval(statusTracker); 
} 

$(function() { 
    $('#progressBar').progressbar({ 
     value: 1 
    }); 
}); 

JSFiddle Demo