对计数器使用setTimeout会产生奇怪的输出吗?

时间:2014-02-18 21:27:19

标签: javascript settimeout

我检查,加倍检查并重新检查此代码以确保它正常工作(并且很简单)但我无法弄清楚为什么我得到 ~count:17k 输出,请帮助..

由于

<html>
<head>  
</head> 
<body onload = "counter()">
<script type="text/javascript">
var count = 0;
function counter()
{
   document.getElementById("div_1").innerHTML = "count: "+count;
   count++;
   setTimeout(counter(), 1000);
}
</script>
<div id = "div_1"></div>
</body>
</html>

3 个答案:

答案 0 :(得分:6)

不要打电话,只需参考

setTimeout(counter, 1000);

答案 1 :(得分:1)

您将counter()的结果传递给setTimout,而不只是setTimeout(counter, 1000)。实际上,它只是一个递归函数。你在做什么是这样的:

var count = 0;
var counter = function(){
    count++;
    //Don't flood the console
    //console.log(count); 
    document.querySelector("#div1").innerHTML = "count: " + count;
    //you probably don't want this
    counter();
    //but this
    //setTimeout(counter, 1000);
};

17k的结果是count在javascript耗尽其调用堆栈时所处的位置

答案 2 :(得分:0)

匿名函数中的Wrap函数

setTimeout(function(){counter()}, 1000);

http://jsfiddle.net/tgLqH/