Hi guys,
if you have an anonymous function sitting within an each function and I would like to use the this parameter within the anonymous function, how would
I do it? Currently it returns an error saying "SyntaxError: missing formal parameter setTimeout(function(this){". I am trying to apply a delay of 1 seconds
to a an image that moves in a new position
Thanks

...
$(".container > a > img").each(function(){
var opacityVal = $(this).css('opacity');
...
setTimeout(function(){
$(this).animate({left:newVal});

},1000);
});

Recommended Answers

All 6 Replies

The definition of setTimeout does not have that parameter, so it would only be possible if you make a new function that would enable this. You can add the jQuery function delay.

$(this).delay(1000).animate({left:newVal});
Member Avatar for stbuchok

You can also try the following (although this is more for educational purposes as pritaeas answer is probably best):

$(".container > a > img").each(function(){
    var opacityVal = $(this).css('opacity');
    ...
    callTimeout(this;)
});

function callTimeout(thisObj){
    setTimeout(function(){
        $(thisObj).animate({left:newVal});
    },1000);
}

Watch out when you work with JavaScript. You should try not to mix pure JavaScript and JQuery syntax together, or you may get the result as you are having right now. I suggest you to use pritaeas way rather than implement it the way stbuchok does even though there is nothing wrong with stbuchok implementation. It is a good practice to do it one way for 2 good reaons -- consistancy and less confusion.

thank you all guys for the suggestions and avices. COuple of things:

The definition of setTimeout does not have that parameter, so it would only be possible if you make a new function that would enable this.

I suppose this translates in what stbuchok has done, another function. But what do you mean exactly by setTimeout not having the "this" parameter? Do you mean that it doesn't accept it in general or just this time because of the way I have construct the function?

You can add the jQuery function delay.

I had a look at the api, and is it correct to say that the delay method might cause problems if you run it too many times, in that it doesn't have the equivalent of the queue: false to stop the animation? For example I am thinking about the above code triggered by a button: if you go click frenzy and click the button 10-15 times then how do I make sure that jquery doesn't go nuts?
thanks

Do you mean that it doesn't accept it in general

Correct.

how do I make sure that jquery doesn't go nuts?

You could start with .stop() stopping all previous animations.

ok thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.