1

I am trying to use jquery ui progressbar. Below is code i have

<!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>

When i am clicking on stop button progress bar do not stop. My clearTimeout() function is not working. Any help will be appreciable .

4

1 回答 1

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 演示

于 2012-12-18T07:03:30.250 回答