0

I am trying to give an object a countdown timer and when the countdown is down it should call a function which removes this object from an array.

array = [];

var object = {
    'name' : 'user',
    'limit' : function() {
         setTimeout(destroyMe(this),10000);
    }
}

array.push(object);

var destroyMe = function(obj) {
    array.remove(obj);
}

I know that there could a problem with the this but the timeout function doesnt work at all not even like this:

var object = {
    'name' : 'user',
    'limit' : function() {
               setTimeout(console.log("dd"),3000);
            }
}

Maybe someone can tell me the issue with my version of the setTimeout. thx

user1354743
  • 407
  • 3
  • 7
  • 20

3 Answers3

7

setTimeout takes a reference to a function. The code you have is calling the function.

This should be changed to:

var object = 
{
    'name' : 'user',
    'limit' : function() 
    {
        setTimeout(function() { destroyMe(this); }, 10000);
    }
}

(You may have issues using this in this context, try it!)

var object = 
{
    'name' : 'user',
    'limit' : function() 
    {
        setTimeout( function() { console.log("dd"); },3000);
    }
}
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
1

You need to pass a function to setTimeout, not a function call.

var object = {
    'name' : 'user',
    'limit' : function() {
         setTimeout(function() { 
             destroyMe(this)
         }, 10000);
    }
};

As you already know, the this probably doesn't do what you are expecting. Replacing destroyMe(this) with console.log("dd") should result in a behavior that you would expect.

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
1

setTimeout either takes a callback (a function, not a function call with arguments) or code in quotes. However, as noted in this question, passing a string is only allowed for historical reasons--there aren't any good reasons for doing it in practice.

But, for completeness sake, one way to do what you want is:

var object = {
    'name' : 'user',
    'limit' : function() {
               setTimeout('console.log("dd")', 3000);
            }
}
Community
  • 1
  • 1
Robz
  • 1,747
  • 5
  • 21
  • 35
  • Please do not suggest passing a string. Ever. There is just not a single acceptable reason to do pass a string instead of a function. Besides that he needs `this` to be preserved. – ThiefMaster Dec 30 '12 at 23:25
  • If mentioning the string passing, you *must* IMO also warn that it's a pretty terrible way to do things. – alex Dec 30 '12 at 23:28