Phillip Senn
Phillip Senn

Reputation: 47625

Passing $(this) in setTimeout

How do I pass $(this) as a parameter in the setTimeout function (method?)? Here'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
    );
});

Upvotes: 2

Views: 7646

Answers (3)

Levite
Levite

Reputation: 17637

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...

Upvotes: 3

Naftali
Naftali

Reputation: 146310

try this:

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

From MPD:

To elaborate on this, read up on Javascript closures

Upvotes: 5

Atanas Korchev
Atanas Korchev

Reputation: 30671

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);
});

Upvotes: 6

Related Questions