开发者

Passing $(this) in setTimeout

How do I pass $(this) as a parameter in the setTimeout function (method?)? He开发者_开发百科re's what I'm doing so far, which is working:

var Variables = {};
Variables.ResizeTimer = false;
Variables.$obj = null;

$('.draggable').resize(function() {
    if (Variables.ResizeTimer !== false) { 
        clearTimeout(Variables.ResizeTimer);
    }
    Variables.$obj = $(this);
    Variables.ResizeTimer = setTimeout(mySizer,
        1000
    );
});


try this:

    Variables.$obj = $(this);
    Variables.ResizeTimer = setTimeout(
         function(){
             mySizer(Variables.$obj);
         },
         1000
    );

From MPD:

To elaborate on this, read up on Javascript closures


Since Variables looks global you can use it inside the mySizer routine. If you don't want to have global variables you can create a closure:

$('.draggable').resize(function() {
    if (Variables.ResizeTimer !== false) { 
        clearTimeout(Variables.ResizeTimer);
    }
    var $this = $(this);
    Variables.ResizeTimer = setTimeout(function() {
        mySizer($this);
    }, 1000);
});


Since no one has mentioned it yet: if you need $(this) only to do something effect-related, you might get away with just using the delay function instead of setTimeout.

$('#some_element').click(function() {

    $(this).delay(2000).fadeIn(); // After 2 seconds, start a fade-in
}

It is also possible to add a function call (for example) to fadeIn. This being useful really depends on your specific use-case though, but it might make things a lot easier if it works for your situation.

Hope this will be helpful to someone...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜