4

Why doesn't this code:

<a href="#">Sample link</a>
<script>
    setTimeout($('a').hide, 2000)
</script>

work like this one:

<a href="#">Sample link</a>
<script>
    setTimeout(function(){ $('a').hide(); }, 2000)
</script>
1
  • @SLaks @Andrea both great answers but IMO Andrea's takes the lead with that link, plus he has a lower score. Wish I could tick both though Commented Feb 24, 2011 at 15:28

4 Answers 4

3

The point is that this is bound to the global object inside setTimeout calls. It follows that both

setTimeout($('a').hide, 2000)

and

setTimeout(function(){ $('a').hide(); }, 2000)

will call the methos $('a').hide, but with different values for this (window in the first case and $('a') in the second).

Here are more details about the value of this according to the way you invoke a function.

Sign up to request clarification or add additional context in comments.

Comments

3

The expression $('a').hide returns jQuery's standard hide function, without any reference to $('a').
When you call $('a').hide() as a statement, $('a') is passed as the this parameter to hide.

However, when you pass the hide function to setTimeout, it doesn't call the function on $('a'); all setTimeout'd functions are called on window.

Comments

2

The problem is this. In JavaScript it's the dot notation used while calling the function that binds this -- so while in you first example you are passing a hide function, it's not connected to any particular jQuery object.

Comments

-2

And if you want that your line of code work, you should quote it:

setTimeout("$('a').hide()", 2000)
OR

Have a look to : http://www.w3schools.com/jsref/met_win_settimeout.asp

1 Comment

I'm assuming this uses eval in the back-end or...?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.