views:

68

answers:

2

I don't know why but this code is not working ? Why would it not ? I guess it is because scope problem I am having here :

function washAway(obj) {
    alert($(obj)); // says HTML Object which is fine
    setTimeout(function() {
        alert($(obj)); // says undefined
        $(obj).fadeOut("slow", function() {              
            $(this).remove();
        });
    }, 2000);
};
+1  A: 

Any ways, I've found my answer after a couple of try/wrong. But I am still wondering why it didn't work out.

Here is the code :

function washAway(obj) {
    alert($(obj).attr("id"));
    var a = function() {
        var _obj = obj;
        return function() {
            $(_obj).fadeOut("slow", function() {
                $(this).remove();
            });
        };
    };

    setTimeout(a(), 2000);
};

Edit : I think I understood the problem here :

Because we are talking about closures here, when washAway execution finishes, the variable obj is destroyed so setTimeOut function callback function can't use that resource because it is no more available on the stack and it is not also a global variable.

Braveyard
+3  A: 

At the point where the function in the timeout executes, it has no way to know what obj is - it was a parameter passed into the method where the timeout was set up, but the function inside has no reference to it.

An alternative approach is to write a jQuery plugin to wait before it acts like this:

function($){ //to protect $ from noConflict()
   $.fn.pause = function(duration) {
       $(this).animate({ dummy: 1 }, duration);
       return this;
   };
}

Then you can use:

$(obj).pause(2000).fadeOut("slow", function() { $(this).remove(); });
David M
Yeah, you are also right. Thanks for the sample code btw.
Braveyard