设置超时没有延迟 [英] No delay with settimeout

查看:95
本文介绍了设置超时没有延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小脚本,并对为什么控制台立即记录所有值而不是将输出延迟到满足超时条件感到好奇...

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆