[英]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: 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);
});
Because you are calling the function. 因为您正在调用该函数。 You should pass a function pointer to setTimeout and not execute the function.
您应该将函数指针传递给setTimeout,而不要执行该函数。
setTimeout(function(){
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
()
. 而是通过使用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);
}
Another way you can do this is using function.bind . 您可以执行此操作的另一种方法是使用function.bind 。
setTimeout(test_obj.init.bind(this, i), i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.