views:

44

answers:

2

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);
+1  A: 

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

setTimeout(callback, msec);
Jason
+1  A: 

@Jason already said how to call the callback correctly.

why is the callback function undefined inside the setTimeout?

When "callback()" is evaluated, the function where you called setTimeout (delay) is finished. The string is evaluated in the global scope where the function callback does not exist (and I think it will always be evaluated in the global scope).

Example:

function a() {
    alert('a');
}

(function() {
    function a() {
        alert('b');
    }
    setTimeout('a()', 1000);
})();

will alert a.


Whereas if you create a closure and evaluate a() inside an anonymous function, it will alert b:

function a() {
    alert('a');
}

(function() {
    function a() {
        alert('b');
    }
    setTimeout(function() {eval('a()');}, 1000);
})();
Felix Kling