停止运行ClearTimeout()的功能

时间:2015-08-06 16:57:13

标签: javascript html

我有两个按钮来启动和停止进度条。这是代码:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0   /jquery.min.js"></script>
</head>
<body>

<form  name="Calculation" method="post">

<progress id="progressBar" value="0" max="100" style="width:300px;">    </progress>

<input type="button" id="btn2" value="Start Acquisition" onclick="progressBarSim(0)">

<input type="button" value="Stop Acquisition" onclick="myStopFunction()">

</form>

<script>

function progressBarSim(al) {

var bar = document.getElementById('progressBar');

bar.value = al;

al++;

 var sim = setTimeout(function(){  progressBarSim(al); }, 50);

}

function myStopFunction() {
clearTimeout(sim);
}

</script>

 </body>

 </html>

我希望通过&#34;停止收购&#34;来取得进展。进度运行期间的按钮。我想ClearTimeout只会在进度完成后才能工作。

1 个答案:

答案 0 :(得分:0)

您的代码更新正确。您需要在函数外声明变量。您需要将脚本更新为以下

var sim; // outside the function
function progressBarSim(al) {
    var bar = document.getElementById('progressBar');
    bar.value = al;
    al++;
    sim = setTimeout(function(){  progressBarSim(al); }, 50);
}

function myStopFunction() {
    clearTimeout(sim);
}

供参考 - http://plnkr.co/edit/F88fYlOklpayfnWNWh9l?p=preview