Reputation: 5356
I have this code, but it execute only once...
$('.' + container).hover(function() {
t = setTimeout( function(elem){
//this should be executed as long as I hover,
//with interval declared in viewSpped variable
$(elem).find('img').first().appendTo('.' + container).fadeOut(500);
$(elem).find('img').first().fadeIn(800);
}(this), viewSpeed);
}...
Any idea what I'm doing wrong? thanks!
Upvotes: 0
Views: 98
Reputation: 382092
setTimeout only call the callback once, that's normal.
Maybe you want setInterval if you want your function to be executed at regular intervals.
And, incidently, there is another error in your code : You probably want
t = setInterval( function(elem){
//this should be executed as long as I hover,
//with interval declared in viewSpped variable
$(elem).find('img').first().appendTo('.' + container).fadeOut(500);
$(elem).find('img').first().fadeIn(800);
}, viewSpeed, this);
The arguments passed by setInterval
or setTimeout
to the callback are after the duration.
Or, to be more compatible (note that the link I provide also gives the workaround for IE) :
var $elem = $(this);
t = setInterval( function(){
$elem.find('img').first().appendTo('.' + container).fadeOut(500);
$elem.find('img').first().fadeIn(800);
}, viewSpeed);
Upvotes: 1
Reputation: 224857
You're calling the function immediately instead of using it as a callback (which wouldn't work anyway, as you need to pass a parameter), and I think you also meant setInterval
.
var elem = $(this);
var container = $('.' + container);
t = setInterval(function() {
elem.find('img').first().appendTo(container).fadeOut(500);
elem.find('img').first().fadeIn(800);
}, viewSpeed);
Upvotes: 1
Reputation: 707158
setTimeout
calls its callback with no arguments. So elem
will NOT be passed to your callback. If you were trying to do a self-invoking function, then all you're doing is calling your function immediately, not passing a callback to setTimeout()
.
I don't know what you expect elem
to be, but if you want it to be the item that was hovered, you would do that like this:
$('.' + container).hover(function() {
var self = $(this);
t = setTimeout( function(){
//this should be executed as long as I hover,
//with interval declared in viewSpped variable
self.find('img').first().appendTo('.' + container).fadeOut(500);
self.find('img').first().fadeIn(800);
}, viewSpeed);
}...
Upvotes: 3