JavaScript控制台陷阱?控制台中的setTimeout返回的值是什么? [英] javascript console gotchas ? what are those values returned by setTimeout in console?
问题描述
在控制台中运行以下代码
When running the following code in console
var ajout1 = function(number) {
number = number || 100;
console.log(number + 1);
}
setTimeout(ajout1, 1000);
setTimeout(ajout1(500), 2000); // evaluates immediately and returns nothing but this is "by design" to show how NOT to write your timeout
setTimeout(function() {
ajout1(1000)
}, 3000);
可能会预期以下结果
t+1: 101
t+2: 501
t+3: 1001
如果您仔细观察,您会发现t2将被立即求值,因此不会等2秒再返回。 (这是设计使然。它教(我)如何不写超时)。因此,预期输出变为:
If you look more closely you'll see that t2 will be immediately evaluated and so will not wait 2 second before returning. (This is "by design". It teaches (me) how not to write a timeout). So the expected output becomes:
t+0: 501
t+1: 101
t+3: 1001
事实上,我真正得到的是
In fact what I really get is
t+0: 501
t+0: <X
t+1: 101
t+3: 1001
X的价值不断增长。
我认为X是timerid,所以我将代码重写为
With X a ever growing value. I think X is the timerid so I rewrote my code as
var t1=setTimeout(ajout1,1000);
var t2=setTimeout(ajout1(500),2000);// no good
var t3=setTimeout(function(){ajout1(1000)},3000);
现在输出为
t+0: 501
t+0: <undefined
t+1: 101
t+3: 1001
如果我评估t1,t2,t3,则其值为X + 1,X + 2,X + 3。所以我猜我的下注X是计时器ID是正确的。
我的问题是为什么控制台只输出1个计数器id而不是3个计数器id的值?为什么我会返回未定义的值。
If i evaluate t1,t2,t3 their values are X+1, X+2, X+3. So i guess my bet X was the timer id is right. My question is why do the console outputs the value of only 1 counter id instead of the three ? Why did I get a "undefined" value returned.
我在Chrome和Edge控制台中进行了测试,结果相同
I tested in Chrome and Edge console with the same results
推荐答案
第二个 setTimeout()
中发生了什么?
What's happening in your second setTimeout()
?
setTimeout(ajout1(500)/*evaluates immediately and returns nothing*/,2000);
然后,该代码如下所示:
And then, that code looks like this:
setTimeout(undefined,2000); //undefined, because ajout1(500) didn't return anything
然后
setTimeout("undefined",2000); //Coerced to string
...以及2秒后...
...and 2 seconds later...
eval("undefined") //Altough not really eval, but similar to it.
这篇关于JavaScript控制台陷阱?控制台中的setTimeout返回的值是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!