tom c
tom c

Reputation: 329

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);
});

Upvotes: 1

Views: 273

Answers (2)

PSL
PSL

Reputation: 123739

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

Upvotes: 2

mohkhan
mohkhan

Reputation: 12305

Because you are calling the function. You should pass a function pointer to setTimeout and not execute the function.

setTimeout(function(){
    test_obj.init(i)
}, i);

Upvotes: 3

Related Questions