Reputation: 10256
I have different classes each with a different background. I'm trying to switch background on div #elm every 2 seconds. Why is the following not delaying 2 seconds between each index. They all come in at once.
var classes = ['class1', 'class2', 'class3'];
$.each(classes, function(index, val) {
$('#elm').removeAttr('class').addClass(val).delay(2000*index);
});
Upvotes: 0
Views: 1030
Reputation: 42818
delay()
only works on effects.
From jQuery delay() documantation
The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.
Since addClass()
is not an effect, you can include a fadeIn() effect and use addclass as a callback function.
var classes = ['class1', 'class2', 'class3'];
$.each(classes, function(index, ui) {
$('body').removeAttr('class').delay(1000).fadeIn(function() {
$(this).addClass(ui);
});
});
Upvotes: 2
Reputation: 47978
this works:
for (var i = 0; i < classes.length; i++) {
setTimeout (
(function(index){
return function(){
$('#elm').removeAttr('class').addClass(classes[index]);
};
})(i), 2000*i);
}
Upvotes: 1
Reputation: 310
Isn't the delay method only for events that use the effects queue, like fading in and out, etc.?
Upvotes: 1