Search code examples
jquerycallbackdelay

Custom jQuery Delayed Callback


I am playing with extending jQuery with a function that has two params: a callback function and a timeout. I'm on pre 1.4 so I don't have the .delay() built-in, but even that isn't really what I want.

I've started out with the below, but am unclear as to

1 why is the callback function undefined inside the setTimeout, and

2 how should I be calling it, if possible?

$.extend({
  delay: function(callback, msec) {

    alert(callback);     // as expected
    alert(msec);         // as expected

    if(typeof callback == 'function'){

      setTimeout("callback()", msec); // why callback() undefined here?!

    }

  }

});

//Usage:
$.delay(function(){
  alert("this is delayed 5sec");
}, 5000);

Solution

  • callback is undefined because you're passing it as a string. do this:

    setTimeout(callback, msec);