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

Comments

comments powered by Disqus
Copyright © 2000-2015 - Eric Abouaf - Powered by Hexo