我检查,加倍检查并重新检查此代码以确保它正常工作(并且很简单)但我无法弄清楚为什么我得到 ~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>
答案 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)