How to set a timer within an object in Javascript

UPDATE: I don’t recommend this method anymore: it’s not a good idea to add functions to Object.prototype. Prefer adding this function to your object prototypes.

Here’s a useful method given by Douglas Crockford that can be added to Object.prototype :

Object.prototype.later = function( msec, method) {
  var that = this;
  var args = Array.prototype.slice.apply( arguments, [2] );

  if( typeof method === 'string' ) {
    method = that[method];
 }
  setTimeout(function() {
    method.apply(that, args);
  }, msec);

  return that;
};

Then, you can call it on any object, the function will be called with the object scope:

myObject.later(1000, "methodName", arg1, arg2, .... ); // call myObject.methodName(arg1, arg2) in 1 second
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>