设置超时没有延迟 [英] No delay with settimeout
问题描述
我写了一个小脚本,并对为什么控制台立即记录所有值而不是将输出延迟到满足超时条件感到好奇...
I wrote a little script and am curious as to why the console logs all of the values immediately versus delaying the output until the timeouts are satisfied...
JS:
var test_obj = {
init: function(i) {
if (i < 10000) {
console.log(i + "<br />");
i = i+i;
setTimeout(test_obj.init(i), i);
}
}
};
$(document).ready(function() {
var i = 1;
test_obj.init(i);
});
推荐答案
这是因为,您没有将函数引用传递给超时.而是通过使用parens ()
调用它来立即调用它. setTimeout(test_obj.init(i), i);
现在,这将调用该函数并将该函数的返回值设置为引用,此处未定义,因为您未返回任何内容.
That is because, you are not passing the function reference to the timeout. instead invoking it immediately by invoking it using parens ()
. setTimeout(test_obj.init(i), i);
now, this will invoke the function and set the return value of the function as the reference which here is undefined as you don't return anything.
相反,请尝试这种方式:
Instead try this way:
init: function(i) {
if (i < 10000) {
console.log(i + "<br />");
i = i+i;
setTimeout(function(){ // Do this way
test_obj.init(i);
}, i);
}
Fiddle
Another way you can do this is using function.bind.
setTimeout(test_obj.init.bind(this, i), i);
Fiddle
这篇关于设置超时没有延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!