Mestore
Mestore

Reputation: 165

setTimeout not delayed with an anonymous function

I'm building a custom slideshow for a project written with jQuery. Each slideshow has 4 events bound to it (play, stop, next, prev). The controls appear on mouseover over and mouseout. On mouseout I want a delay in the controls disappearing. To achieve this I used a setTimeout.

$(this).attr('timeout', setTimeout((function(obj){obj.fadeOut(250);})($(this)), 1000));

This is however causing a 'useless setTimeout call (missing quotes around argument?)' error

I removed the ($(this)) to see if I could simplify things.

$(this).attr('timeout', setTimeout((function(foo){alert(foo);})('bar'), 1000));

This caused 'bar' to be displayed in the alert message box on mouseout without a delay, or any errors reported in firebug. I can only assume by this logic that the anonymous function is being run right away which leaves nothing for the setTimeout to call later.

If I ignore the need to pass $(this) into the anonymous function and try

$(this).attr('timeout', setTimeout(function(){alert('foo');}, 1000));

everything works as expected, I must be doing something wrong with the syntax of the anonymous function but I'm out of ideas as to what it might be.

Thanks

Upvotes: 2

Views: 1511

Answers (1)

Nick Craver
Nick Craver

Reputation: 630379

Since you're using jQuery, just use $.proxy() to set the call contenxt, like this:

$(this).attr('timeout', 
  setTimeout($.proxy(function(){ $(this).fadeOut(250); }, this), 1000));

Note though this isn't a valid attribute, it's better to store things like this in .data(), like this:

$(this).data('timeout', 
  setTimeout($.proxy(function(){ $(this).fadeOut(250); }, this), 1000));

Or this:

$.data(this, setTimeout($.proxy(function(){ $(this).fadeOut(250); }, this), 1000));

The problem with your current method is that this is self-invoking:

(function(foo){alert(foo);})('bar')

Where you want to return a function with the right context...more concisely done with $.proxy() above in your case.

Upvotes: 2

Related Questions