开发者

Custom jQuery Delayed Callback

I am playing with extending jQuery with a function that has two params: a callback func开发者_开发知识库tion 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);


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

setTimeout(callback, msec);


@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);
})();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜