Skip to content Skip to sidebar Skip to footer

Execute A Method On An Existing Object With Window.setinterval

Is it possible to run the method on an existing object on timeout of window.setInterval method. I can emulate the same by having some global variable and calling the method of this

Solution 1:

Yes, you can do this. You need a helper function to make a new function that has your existing object "bound":

var someRandomObject = {
  someMethod: function() {
    // ... whatever
  },
  // ...
};

// this is a "toy" version of "bind"functionbind(object, method) {
  returnfunction() {
    method.call(object);
  };
}

var interval = setInterval(bind(someRandomObject, someRandomObject.someMethod), 1000);

Now when the interval timer calls your method ("someMethod"), the "this" pointer will reference the object.

That version of "bind" is simplified. Libraries like Prototype, Functional, jQuery, etc generally provide more robust versions. Additionally, the "bind" function will be a native part of Javascript someday — it already is in some browsers.

Post a Comment for "Execute A Method On An Existing Object With Window.setinterval"