Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jun 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Using setInterval for an object's method

    Hi experts,

    I have defined an object's prototype named InfoObject which contains a method start() as a member method

    function start(){
    setInterval("this.increment()", 5000);
    }

    where increment() is another member method in the same InfoObject object type.

    function increment(){
    this.val += 10;
    }


    When i invoke start method on the object, I do not get intended result. increment method gets called again and again but it gived an error since "this" pointer (which refers to window object when the call is made), does not contain val field.

    Here I can not use a global reference the object instead of "this" because I have defined this InfoObject in a different .js file. I include this .js file in my different html pages and create one or more instances of this InfoObject.

    What I want?
    Whenever I call start() on a object, it should put an invocation to
    increment() method on a repeated invocation mode, so that increment() gets repeatedly called on the same object after a particular interval.

    Please suggest me a way to achieve this.

    Regards,
    Pushker Chaubey

  • #2
    Banned
    Join Date
    May 2006
    Location
    England
    Posts
    664
    Thanks
    0
    Thanked 84 Times in 84 Posts
    Quote Originally Posted by pushker.chaubey View Post
    What I want?
    Whenever I call start() on a object, it should put an invocation to
    increment() method on a repeated invocation mode, so that increment() gets repeatedly called on the same object after a particular interval.
    Try this:
    Code:
    function start()
    {
      setInterval( (function(inst){return function(){inst.increment()}})(this), 5000);
    }
    This is how I would use it:
    Code:
    InfoObject=function()
    {
     this.val=0;
     
     this.start=function()
     {
      setInterval( (function(inst){return function(){inst.increment()}})(this), 5000);
     }
    
     this.increment=function()
     {
      this.val += 10;
      document.title=this.val;
     }
    
    }
    
    new InfoObject().start();
    Last edited by Arty Effem; 06-13-2008 at 06:13 PM.

  • #3
    Regular Coder
    Join Date
    May 2008
    Posts
    187
    Thanks
    7
    Thanked 7 Times in 7 Posts
    That looks like a hack if I've ever seen one.


  •  

    Posting Permissions

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