循环中停止setTimeout的方法
在HTML编程中,有时候需要按单位时间不停的执行某个方法,我会用到setTimeout这个函数。如下
<script type="text/javascript">
var c=0;
var t;
function timedCount()
{
c=c+1;
document.getElementByIdx('txt').value=c;
t=setTimeout("timedCount()",1000);
}
</script>
上面的意思是:每隔1 秒,变量c加1并赋值到id为txt组件的value。
如果想停止setTimeout的执行有什么方法呢?,将上面的代码改为:
<script type="text/javascript">
var c=0;
var t;
function timedCount()
{
c=c+1;
document.getElementByIdx('txt').value=c;
t=setTimeout("timedCount()",1000);
}
function stopCount()
{
clearTimeout(t);
}
</script>//调用stopCount()的方法上面一秒执行一次timedCount()的就会停止。

浙公网安备 33010602011771号