为什么这个js代码可以循环

Why this js code can loop?

本文关键字:循环 代码 js 为什么      更新时间:2023-09-26
<script type="text/javascript">
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",1000)
}
</script>
<input type="button" value="begin to count!" onClick="timedCount()">
<input type="text" id="txt">

函数 timedCount 中没有循环,但是当我点击按钮时,id='txt' 的值会不断增加吗?

由于setTimeOut您的 timedCount() 函数在您设置的每个1000ms之后执行。如果你想停止循环,请使用 clearTimeout((;功能。

喜欢:

t=setTimeout("timedCount()",1000)
clearTimeout(t); //it clears the time out function iteration. 

更新

您可以调用不带引号setTimeOut函数:

function timedCount() {
    document.getElementById("txt").value = c;
    c++;
    t = setTimeout(timedCount, 1000);
}

或使用匿名函数:

t = setTimeout(function() {
    document.getElementById("txt").value = c;
    c++;
}, 1000);

参考:

  • 设置超时
  • 清除超时

这是由于递归原则而发生的。

此代码永远不会终止,因为在方法有机会退出之前,会再次调用该方法。

function method()
{
  method();
}

这与你提供的代码非常相似。

你的timedCount函数在每一秒后调用一次,所以你的变量会增加。设置超时在javascript中用作计时器控件。

js timeout 方法在指定的时间量后调用函数一次,因为您在指定的时间后再次调用同一函数,这会导致对超时函数的另一次调用,将该过程重复为循环或递归。

function timedCount()
{
     document.getElementById('txt').value=c
     c=c+1
     t=setTimeout("timedCount()",1000)
 }

这里 timedCount(( 每次在这些函数中调用时。 所以它是无限循环。