SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Enthusiast Aquis's Avatar
    Join Date
    Jun 2006
    Location
    Uttoxeter, Staffordshire, UK
    Posts
    38
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to setTimeout("this.doSomething()",10)?

    Hello,

    I have a custom object and in one of the methods of this object, I need to setTimeout to the method it's currently executing. Basically, so far, I've got:
    Code JavaScript:
    setTimeout("this.move()",10);
    But it doesn't work! The reason for this I believe is that when it is time for the timer to activate, it's no longer in the object, and therefore "this" doesn't exist anymore. When executing, I'm told that "this.move is not a function".

    The only way I can think of solving this is to record all of the instances into an array and use a global function to target the correct instance, but I would prefer to get this to work...

    Thanks,
    Aquis

  2. #2
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    try

    Code:
    setTimeout(function() {
    this.move();
    }, 10);


  3. #3
    SitePoint Evangelist
    Join Date
    Jul 2007
    Posts
    345
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Before calling setTimeout you can assign this to another variable and use that instead.
    Code:
    var me = this;
    setTimeout(function(){me.move()}, 10);

  4. #4
    SitePoint Enthusiast Aquis's Avatar
    Join Date
    Jun 2006
    Location
    Uttoxeter, Staffordshire, UK
    Posts
    38
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    gRoberts - Really thought that was going to work for a second there, but it unfortunately did not...

    r51 - The problem with this is that quite a few instances will all be doing this. Actually, that might work as an array, but it could get big and messy, however I'll try that for now...

    Thanks!

  5. #5
    SitePoint Guru
    Join Date
    Mar 2004
    Location
    Earth
    Posts
    406
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    what r51 said is what you need to do - "this" will point to window inside an interval, so you need to copy the reference into the parent scope and use that, exactly as demonstrated

  6. #6
    SitePoint Enthusiast Aquis's Avatar
    Join Date
    Jun 2006
    Location
    Uttoxeter, Staffordshire, UK
    Posts
    38
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hmm, okay, I'll give it a try then...

    Robert

    Edit: I guess you were right, it worked! I'll have to bear that in mind in future...

    Thanks All!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •